Compare commits

...
46 Commits
Author SHA1 Message Date
erikbrockoandClaude Opus 5.5 d96339b72b Desktop: Customize Toolbar window
test / test (push) Has been cancelled
Right-clicking the toolbar now offers Customize Toolbar…, laid out like
the official window: a searchable tree of available actions by category,
the selected actions list, arrow buttons, drag and drop, and Reset to
Defaults. Changes apply live and are kept in the toolbarLayout setting,
empty standing for the default layout.

The toolbar is built from that layout out of 68 actions over connection,
self, dialogs, permissions, recording, channel, client and misc. Channel
actions act on the selected channel (or the selected client's, else our
own), client actions on the selected clients; buttons follow the tree
selection. Actions without a pack icon show their name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 07:08:19 +00:00
erikbrockoandClaude Opus 5.5 212a4bcdbb myTeamSpeak docs: the synced config item, sync edge cases and limits
CONFIG_SYNC.md lists the class 5 config item's fields; none maps onto a
setting of ours, so sync leaves it alone. IMPLEMENTATION.md covers the
session lock, duplicate keys in the account, bookmarks following an
identity's conflict, interrupted runs, and what sync cannot catch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 22:04:26 +00:00
erikbrockoandClaude Opus 5.5 f6fbc6e40c myTeamSpeak: sign-ins no longer block the UI; sync fixes
Signing in held the login's lock across its requests, so asking whether
we are signed in waited for the network, up to a minute and more on a
throttled account; the session now has a lock of its own.

An identity whose key another account item already stands for is left as
the account has it, instead of merged into ours and written back over the
other. A bookmark that only lost an identity deleted here follows how
that identity's conflict is settled, rather than dropping the link even
when the identity is kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 21:45:59 +00:00
erikbrockoandClaude Opus 5.5 1f61ad0b29 Android: Synchronize with myTeamSpeak; keep each installation's default identity
Settings → myTeamSpeak gets Synchronize, with conflicts settled in
SyncConflictsScreen. The default identity is no longer a synced field:
an identity new to the account carries it only when the account has
none, and one brought here takes it only when we have none, so
installations stop flipping each other's default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 16:37:04 +00:00
erikbrockoandClaude Opus 5.5 116986c6fc Desktop: Synchronize with myTeamSpeak, with a conflicts window
Options -> myTeamSpeak gains Synchronize. Items changed here and in the
account since the last run are listed field by field, the differences in
bold, each kept from one side; nothing changes until all are settled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 12:37:50 +00:00
erikbrockoandClaude Opus 5.5 756e3850a3 myTeamSpeak: two-way sync of bookmarks and identities
MyTeamSpeakSync compares each item against what the last run left: a
change on one side goes to the other, deletions too, and an item changed
on both sides is a conflict for the user. The first run pairs items up by
identity key or bookmark name and address. Edits are written over the
item's Item_Data field by field, so what we do not model survives.

The protocol was probed live and checked against the official client:
the server stores whatever revisions it is sent and never reports a
collision, so the client re-reads the cursors before writing. Edits carry
last_known_version like the official client's, which applies them within
its one-minute poll. All requests now share one session; signing in for
each got the account's logins throttled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 12:37:50 +00:00
erikbrockoandClaude Opus 5.5 ab6bf30003 Link addresses written without a scheme, over https
Servers write [url=www.teamspeak.com]; it showed as raw BBCode. An address
without a scheme now opens over https, as bare www. text in a message does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 20:32:18 +00:00
erikbrockoandClaude Opus 5.5 0043c03410 Desktop: no exceptions when servers report leaving after shutdown
Quitting from the shutdown hook (SIGTERM) leaves every server, whose
disconnects then reach the mic hand-over and the notifier after their
threads have stopped. Both now drop work that comes in that late.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 20:30:11 +00:00
erikbrockoandClaude Opus 5.5 e9110c2767 Audit: note that an upload counts as done before the server has it
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 20:17:56 +00:00
erikbrockoandClaude Opus 5.5 d61e96a07f ts3j: pad a short RSA puzzle answer instead of failing the connect
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 20:17:56 +00:00
erikbrockoandClaude Opus 5.5 8239a41c6a Report leaving a server once
Our own leave also fires the socket's disconnect event, queued, so it was
reported twice, and a late one could tear down a reconnect already under way.
The event now counts only for the current socket, and not while we leave.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 20:17:56 +00:00
erikbrockoandClaude Opus 5.5 cdbf051ca6 Android: don't crash on connect on Android 13
ChatFeed used Stream.toList(), which Android only has from API 34.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 20:17:56 +00:00
erikbrockoandClaude Opus 5.5 902f036ba0 Structural audit: record 12's commit; defer 13 and 14
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 18:47:16 +00:00
erikbrockoandClaude Opus 5.5 7e794ffffe Swing ui package split by feature
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 18:34:12 +00:00
erikbrockoandClaude Opus 5.5 6070160fb6 Android servers get their shared parts from ServerParts, not SessionController
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 18:25:51 +00:00
erikbrockoandClaude Opus 5.5 382d76c3d8 Android app-wide stores out of SessionController; screens take only their parts
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 20:55:08 +00:00
erikbrockoandClaude Opus 5.5 78b66ef346 Android ServerScreen state in holders: nav, find, picking; overlays apart
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 20:35:45 +00:00
erikbrockoandClaude Opus 5.5 a2a12804ad Chat lines are routed once, in core
session.ChatFeed decides which conversation a message, history, server
event or notice goes to and renders it; frontends get the lines through
chat.ChatSink and key conversations by chat.ChatKey. ServerSession.Listener
no longer passes on raw chat events. Swing now labels our own messages
with our nickname on the server and links our name to us in private chats.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 23:37:33 +00:00
erikbrockoandClaude Opus 5.5 53585994a8 One byte-size format and one chat scope
text.ByteSize writes sizes and rates as TeamSpeak does and replaces the
formatters in ChatHtml, FileBrowserDialog and ConnectionStatsFormat.
chat.ChatScope replaces ConnectionListener.ChatScope, ChatLogScope and
ChatPanel.Target, and the mappings between them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 23:01:42 +00:00
erikbrockoandClaude Opus 5.5 203082d040 Settings values are Setting<T>: one key each, change listeners
Each setting is declared once with its key, type and range, and loaded
and saved from that list. Output device, volume and receive buffer, the
status bar and the master volume slider take effect through listeners
instead of calls wherever they change; Android does the same for output
settings and country flags. The Playback page previews voice volume with
the master volume applied.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 22:53:37 +00:00
erikbrockoandClaude Opus 5.5 bbe741d5cf Name abstract base classes Abstract*; no null as "nothing" in list windows
ServerListDialog, ListEditorDialog and CtlOpusEncoder gain the Abstract
prefix. The list windows blank their status line with clearStatus() and
make icon-less menu items with item(text, action), instead of passing null.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 21:36:37 +00:00
erikbrockoandClaude Opus 5.5 e214f2141e Server list windows share one ServerListDialog base
The ban list, complaints, privilege keys, offline messages and server
log windows each built the same frame, title, status line, key bindings,
load guard and reload-after-change. ServerListDialog does that once;
ServerTab keeps the open windows in one map.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 21:36:16 +00:00
erikbrockoandClaude Opus 5.5 f7cf0401e4 Menu bar, toolbar and hotkeys share one set of commands
MainCommands holds each command once: the plain ones act on the server
on screen, the ones taking a list of sessions serve hotkeys, which reach
the selected server or every connected one. The menu bar, toolbar and
HotkeyActions call it directly, so both Listener interfaces and the
forwarding in MainFrame are gone.

The menu's mute items no longer click the toolbar's buttons, and its
commander toggle now repaints the toolbar and tray.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 21:14:31 +00:00
erikbrockoandClaude Opus 5.5 de42429d08 Frontends reach a server only through ServerSession
session.connection() is gone: the session hands out the model, our ids,
the microphone and speakers, ping and connection info, the server's
unique id, icon and avatar stores, myTeamSpeak, the connect error and a
blocking disconnectNow. The connection's remaining actions move into
helpers the session hands out instead of forwarding each method:
ClientAdmin (move, kick, ban, groups, talk power, poke, client details),
ChannelFiles (listing, mkdir, rename, delete, transfers and their
sounds) and ClientContacts (display names, volume, auto-mute, whisper
policy, sightings); ChannelAdmin also takes join, move, subscribe and
description requests. Dialogs take the session instead of the
connection.

Android's network handover now uses disconnectNow, which also cancels a
pending auto-reconnect.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 20:58:25 +00:00
erikbrockoandClaude Opus 5.5 9107bdd02e Move our own state out of TeamspeakConnection: OwnClient, Recording
OwnClient owns the microphone and speakers and our flags (mute, deafen,
away, commander, talk request, phonetic nickname, input hardware) and
publishes them; Recording owns the recorder. ServerSession reads the
flags from OwnClient instead of keeping its own copy, and they are now
cleared when a connect starts rather than once it is done.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 19:04:01 +00:00
erikbrockoandClaude Opus 5.5 c2090d8122 Keep ini4j's reflectively created constructors in release builds
R8 stripped IniParser's no-arg constructor, which ini4j's ServiceFinder
instantiates by reflection, so reading identities (myTeamSpeak login,
import) crashed the release build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 18:48:59 +00:00
erikbrockoandClaude Opus 5.5 959f7ed97a Frontends call the admin helpers directly, not through the connection
The channel, ban, privilege key, complaint, server log, offline message
and avatar helpers are public, each method running in the background and
answering a future; only the connection creates them. TeamspeakConnection
and ServerSession hand them out, which drops 30 one-line forwarders from
the connection. What the forwarders added moves into the helpers: the
stop-at-the-first-refusal loops, the "sent" log lines, re-reading an
edited channel's description and showing our own new avatar. The
complaint and offline message length limits move with them.

The icon chooser and the offline message composer take only their
helper; the other dialogs still need the connection for the model.

The connection's request runner is renamed Uplink, since
session.ServerLink is the ts3server:// link.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 18:45:21 +00:00
erikbrockoandClaude Opus 5.5 da908f77bd Run server requests through ServerLink, not the whole connection
ServerLink owns what lives from one connect to its teardown: the socket,
the thread ts3j dispatches events on, the threads requests run on and
the file transfer channel. It runs requests in the background and says
whether we are connected. The *Admin helpers take it, plus the model,
permissions or avatar store where they need them, instead of the whole
TeamspeakConnection; the connection's file transfer calls share its
"not connected" check instead of repeating it.

A myTeamSpeak refresh that fails because we left meanwhile is no longer
reported, as for every other request.

Also corrects 4a's commit hash in AUDIT-STRUCTURE.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 18:40:11 +00:00
erikbrockoandClaude Opus 5.5 1bc7eb58c1 Move the chat log and announcements out of TeamspeakConnection
ChatLog opens the on-disk log once the server is known, hands frontends
the server and channel history, and saves sent and received messages and
the server tab's log lines; with logging off, everything still reaches
the app unsaved. Announcer tells the user what happened as TeamSpeak
does: the server-tab line with linked channels and clients, the sound
pack's sound with its name variables, and errors with the matching
"insufficient permissions" or "error" sound.

ConnectionEventHandler uses both directly instead of nine helpers on the
connection, which no longer holds the sound notifier. The connection's
public API is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 18:11:23 +00:00
erikbrockoandClaude Opus 5.5 13e3a62042 Answer what we may do in one place: Permissions
The rules were spread over ServerSession's can* methods, ServerModel's
permits/mayHavePower/canDelete*, TeamspeakConnection and AvatarAdmin, and
Swing dialogs and Android's ServerController passed raw permission names.
Permissions now holds the server's permission table and the rules (offered
until the server says, unreported powers unknown until asked) and answers
one named question per capability. ServerSession.permissions() is the gate
for frontends: Permissions.NONE, allowing nothing, while disconnected.
ServerController's forwarding properties go the same way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 16:53:11 +00:00
erikbrockoandClaude Opus 5.5 e255a4669c Parse a client's properties once, for joins and updates alike
onClientJoin set every field and onClientChanged set the same ones again
behind presence checks, so the two drifted: a client entering as channel
commander showed as none until they toggled it, and the description they
entered with was dropped. applyClientProperties now maps each field once,
only when the event carries it, as applyChannelProperties does for
channels; the update keeps its side effects (info refresh, contacts,
unread count, announcements).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 16:47:34 +00:00
erikbrockoandClaude Opus 5.5 0552ed8be6 Requests return futures that fail with a typed RequestException
Server requests on TeamspeakConnection took callbacks given a value and an
error string, null on success, so frontends told a permission refusal from
other failures by the message's wording (ban list, server log) and core
needed a sentinel message for a refused search. They now return a
CompletableFuture that fails with a RequestException carrying the kind
(not connected, permission, failed) and the server's reason.

Replies hands the outcome to a success or a failure handler on a given
executor; Swing's Edt runs them on the event thread, so call sites no
longer marshal by hand. Android's ServerController, whose suspend calls
answered a String? that was null once done, returns Result instead.
lookupDatabaseClient answers an Optional rather than null.

Starts the structural audit in AUDIT-STRUCTURE.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 16:25:07 +00:00
erikbrockoandClaude Opus 5.5 985c54a362 Android: one APK for both ABIs in releases too
Drops the per-ABI release splits for abiFilters on arm64-v8a and x86_64.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 15:56:34 +00:00
erikbrockoandClaude Opus 5.5 4ce78e9b29 Android: swipe between tree and chat, servers, and chat tabs
A sideways swipe over the channel tree turns to the chat (lying to its
right) or to the neighbouring connected server, as picked in Design
settings ("Swipe sideways": off, channel tree and chat, connected
servers). A swipe over the chat lines goes to the neighbouring tab, on
by default, and the tab row scrolls it into view. The page beside the
one on show follows the finger (SwipeHost); a swipe with nowhere to go
is left to the host further out, so the chat's tabs hand over to the
chat/tree swipe at either end. The choices are Android-only, kept in
their own SharedPreferences (SwipePrefs).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 15:56:34 +00:00
erikbrockoandClaude Opus 5.5 13c1e8a659 Reconnect on desktop after a dropped connection
After a timeout or a server shutdown the session counts down and connects
again, back to the channel it was in, waiting 5, 10, 20, 40 and then 60 s
between attempts. A kick, a ban, leaving, or connecting elsewhere ends it, as
does a retry refused with a ban. The status bar shows the countdown with a
Cancel link. Off by default in core, so Android keeps its own NetworkFollower.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 01:30:14 +00:00
erikbrockoandClaude Opus 5.5 b7a5828c43 Remember the window's place and the tree/chat divider
The main window comes back at its last size and position, maximised if it was;
a place no longer on any screen falls back to the default. The tree/chat
divider is saved like the tree/info one, and both keep their share of the
window as it is resized.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 01:30:14 +00:00
erikbrockoandClaude Opus 5.5 a57700959f Request, grant and revoke talk power
Core keeps client_is_talker, the request's time and reason, and each
channel's needed talk power; clientedit grants or revokes, and "grant
next" picks whoever in our channel asked first, optionally revoking the
rest. The server refuses a request or a grant ("invalid parameter") from
or for a client that can already talk, so both are offered only to those
short of talk power. Grants dropped without an invoker (leaving the
channel, the channel's need changing) are not announced. Verified on a
local 3.13.7 server.

Desktop: Grant/Revoke Talk Power in the client menu, also for several
selected clients; the tree's badges in TeamSpeak's order (granted or
insufficient ahead of the groups, a request after them); the request's
reason in the info panel; log lines; the three talk power hotkeys. The
Self menu's request item shows only while it is needed.
Android: grant/revoke among the client sheet's admin actions, request or
cancel on our own sheet, the same badges in the tree.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 01:15:39 +00:00
erikbrockoandClaude Opus 5.5 204cbd6048 Android: client sheet's admin actions behind "Admin actions…"
Move to channel, the kicks, the ban and the group pickers move under one
row that, once tapped, gives its place to them, raises the sheet and
scrolls them into view (ExpandableAction). The row shows only when one of
them is ours to use; "Move to own channel" stays in the main list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 00:51:05 +00:00
erikbrockoandClaude Opus 5.5 7fde4f502a Offer move/kick/ban when the server won't tell our powers
Asking for i_client_move_power and the like (permget) needs
b_client_permissionoverview_own, which custom moderator groups often lack
although they hold the powers; servergrouppermlist is refused too. A
refusal counted as 0, so Android hid actions the official client allows.
Now a refusal means unknown and the actions are offered, as the official
client always does, leaving the server to judge; only an answered 0 hides
them. Verified with such a group on a local 3.13.7 server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 00:50:58 +00:00
erikbrockoandClaude Opus 5.5 c41b86f704 Select several clients in the tree to move or kick them together
Desktop: Ctrl/Shift in the tree (ClientSelectionModel keeps a selection to
one row of any kind or several clients; a Shift range keeps its clients),
drag them onto a channel, or right-click for Kick Clients from Channel /
Server and Move Clients to own Channel. The selection survives rebuilds.
Android: long-press a client, tap more; a bar offers Move to…, Move to my
channel and both kicks (as far as we may), Back clears it.

Core sends one piped clientmove / clientkick. The server refuses the whole
pipe when one row fails ("already member of channel"), so it leaves out
clients already in the target, and for a channel kick those already in
the default channel, which the model now tracks (channel_flag_default).
Verified on a local 3.13.7 server with both frontends.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 00:50:32 +00:00
erikbrockoandClaude Opus 5.5 96e926168c Android: reorder the client sheet
Connection info moves to the end, just above the volume slider, which
stays last; "Add to whisper list…" is left out of the sheet for now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 21:13:39 +00:00
erikbrockoandClaude Opus 5.5 3948db69bb Bookmarks: "this channel" button instead of the channel's "Add to bookmarks"
The bookmark editors (desktop dialog, Android screen) get TeamSpeak's
button beside the default channel, with its MAKE_CURRENT_CHANNEL_DEFAULT
icon: it takes the channel we are in, enabled while we are on the server
the form's address and port lead to (Sessions.connectedTo). The Android
channel sheet drops "Add to bookmarks"; the server sheet keeps it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 21:03:04 +00:00
erikbrockoandClaude Opus 5.5 173e710960 Android: per-bookmark "Show whisper controls", off by default
Whispering can't be gated on permissions: our i_client_whisper_power is
never reported (and guests may not permget it), and whether a whisper gets
through depends on the target's needed whisper power, which clients can't
see. So the whisper menu and the Whisper / Add to whisper list actions are
shown only for servers connected from a bookmark that asks for them; an
edit of that bookmark applies without reconnecting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 21:03:00 +00:00
erikbrockoandClaude Opus 5.5 d3731e297b Hide "Browse files" without the permission to list files
The channel menu (desktop) and channel sheet (Android) leave the entry out
when i_ft_file_browse_power is 0. Unlike move/kick/ban powers it is among the
needed permissions the server reports, and with it at 0 ftgetfilelist is
refused even where the channel needs no power (verified on a local 3.13.7).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 21:02:45 +00:00
erikbrockoandClaude Opus 5.5 801dfa39ab myTeamSpeak: announce the account ID to servers
Signs clientinit with the account's Ed25519 key over the connection
challenge, honours the per-bookmark switch, sends updatemytsid on
sign-in/out, and connects without the ID when myTeamSpeak is unreachable.
Verified live against server.lixko.eu.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 20:04:59 +00:00
erikbrockoandClaude Opus 5.5 ca86c510b7 myTeamSpeak: import TeamSpeak 6 contacts; bookmark myTeamSpeak switch
TeamSpeak 6 syncs chat contacts as item class 8 (Item_Data field 25). They
are imported as friends keyed by myTeamSpeak ID, taken from the item or from
the partner's chat ID (@<base32 id>:<homeserver>), the same bytes servers
report as base64 client_myteamspeak_id. The contact list matches them to
clients through the ID each client carries.

Bookmarks gain TeamSpeak's "Enable myTeamSpeak features" switch
(send_mytsid_on_server), stored and imported but not yet sent; what is
still missing is noted in docs/myteamspeak/myteamspeak_server_signin.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-10 17:56:29 +00:00
275 changed files with 14037 additions and 6950 deletions
+3 -9
View File
@@ -87,6 +87,9 @@ android {
targetSdk = 36 targetSdk = 36
versionCode = 1 versionCode = 1
versionName = "0.1.0" versionName = "0.1.0"
ndk {
abiFilters += listOf("arm64-v8a", "x86_64")
}
} }
signingConfigs { signingConfigs {
@@ -101,15 +104,6 @@ android {
} }
// One APK per ABI for releases; debug builds stay a single APK for both. // One APK per ABI for releases; debug builds stay a single APK for both.
splits {
abi {
isEnable = gradle.startParameter.taskNames.any { it.contains("Release") }
reset()
include("arm64-v8a", "x86_64")
isUniversalApk = false
}
}
buildTypes { buildTypes {
release { release {
signingConfig = signingConfigs.findByName("release") signingConfig = signingConfigs.findByName("release")
+4
View File
@@ -8,3 +8,7 @@
# ts3j builds protocol handlers and packet bodies reflectively. # ts3j builds protocol handlers and packet bodies reflectively.
-keep class com.github.manevolent.ts3j.** { *; } -keep class com.github.manevolent.ts3j.** { *; }
# ini4j (identity .ini files) instantiates its parsers, builders, formatters
# and escape tools through ServiceFinder, by reflection.
-keepclassmembers class org.ini4j.spi.** { <init>(); }
@@ -0,0 +1,36 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import eu.lixko.ts3j.client.config.BanReasonPresets
import eu.lixko.ts3j.client.config.Bookmarks
import eu.lixko.ts3j.client.config.IdentityStore
import eu.lixko.ts3j.client.config.Settings
import eu.lixko.ts3j.client.contacts.ContactStore
import eu.lixko.ts3j.client.teamspeak.TeamSpeakImporter
/** What lives as long as the process, wired together once; each screen is handed only the parts it uses. */
class AppParts(context: Context) {
val settings: Settings = Settings.load()
val icons = IconTheme(context, settings)
val pictures = WebPictures(context.cacheDir, settings)
val swipe = SwipePrefs(context)
/** The reasons offered when adding a ban; shared by every server. */
val banReasons: BanReasonPresets by lazy { BanReasonPresets.load() }
private val bookmarkStore = Bookmarks.load()
private val identityStore = IdentityStore.load(settings)
private val contactStore = ContactStore.load()
val identities: IdentityManager = IdentityManager(context, identityStore, settings, bookmarkStore) { bookmarks.refresh() }
val bookmarks: BookmarkManager = BookmarkManager(context, icons, bookmarkStore, identities) { sessions.bookmarkEdited(it) }
val contacts: ContactManager = ContactManager(context, contactStore, settings)
val whisperLists: WhisperListManager = WhisperListManager()
val audio: AudioSetup = AudioSetup(context, settings)
val myTeamSpeak: MyTeamSpeakAccount = MyTeamSpeakAccount(context, pictures,
TeamSpeakImporter(identityStore, bookmarkStore, settings, contactStore), bookmarks, identities,
identityStore, bookmarkStore, settings) { sessions.myTeamSpeakChanged() }
private val serverParts = ServerParts(context, settings, identityStore, audio, contactStore, myTeamSpeak)
val sessions: SessionController = SessionController(context, settings, identities, bookmarks, serverParts,
LevelMonitor(settings, audio.audio))
}
@@ -0,0 +1,76 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import eu.lixko.ts3j.client.android.audio.AndroidAudioBackend
import eu.lixko.ts3j.client.android.audio.AudioRoute
import eu.lixko.ts3j.client.audio.AudioDevice
import eu.lixko.ts3j.client.config.Settings
import eu.lixko.ts3j.client.sound.SoundNotifier
import eu.lixko.ts3j.client.sound.SoundPack
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
/** The devices and routing audio goes through, the sound packs, and the floating push-to-talk button. */
class AudioSetup internal constructor(private val context: Context, private val settings: Settings) {
internal val audio = AndroidAudioBackend(context)
private val soundPlayer = SpeakingSoundPlayer(context, audio.createSoundPlayer(settings))
internal val sounds = SoundNotifier(settings).also { it.setPlayer(soundPlayer) }
private val routePrefs = AudioRoutePrefs(context)
private val _route = MutableStateFlow(routePrefs.load())
val route: StateFlow<AudioRoute> = _route
private val _inputDevices = MutableStateFlow(audio.io().inputDevices())
val inputDevices: StateFlow<List<AudioDevice>> = _inputDevices
private val _outputDevices = MutableStateFlow(audio.io().outputDevices())
val outputDevices: StateFlow<List<AudioDevice>> = _outputDevices
val unprocessedSupported: Boolean get() = audio.unprocessedSupported()
init {
audio.setRoute(_route.value)
audio.addDeviceListener {
_inputDevices.value = audio.io().inputDevices()
_outputDevices.value = audio.io().outputDevices()
}
settings.outputDevice.addListener { soundPlayer.setOutputDevice(it) }
}
/** Microphone preset and playback usage; the open lines move over at once. */
fun setRoute(route: AudioRoute) {
routePrefs.save(route)
_route.value = route
audio.setRoute(route)
}
private val _soundPacks = MutableStateFlow(sounds.availablePacks())
val soundPacks: StateFlow<List<SoundPack>> = _soundPacks
val soundPack: SoundPack? get() = sounds.pack()
fun setSoundPack(pack: SoundPack) {
sounds.setPack(pack)
settings.save()
}
/** Unpacks the packs the app ships with, when this version has not yet. */
fun installSoundPacks() {
if (!SoundPackInstaller(context).install()) return
sounds.reload()
_soundPacks.value = sounds.availablePacks()
}
private val overlayPrefs = context.getSharedPreferences("overlay", Context.MODE_PRIVATE)
private val _pttOverlay = MutableStateFlow(overlayPrefs.getBoolean(OVERLAY_ENABLED, false))
/** Whether push to talk floats a button over other apps while this one is off screen. */
val pttOverlay: StateFlow<Boolean> = _pttOverlay
fun setPttOverlay(enabled: Boolean) {
overlayPrefs.edit().putBoolean(OVERLAY_ENABLED, enabled).apply()
_pttOverlay.value = enabled
}
private companion object {
const val OVERLAY_ENABLED = "enabled"
}
}
@@ -0,0 +1,99 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import android.os.Handler
import android.os.Looper
import eu.lixko.ts3j.client.config.Bookmark
import eu.lixko.ts3j.client.config.Bookmarks
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
/** The bookmarks, as the connect page lists them and home-screen shortcuts lead to them. */
class BookmarkManager internal constructor(
context: Context,
icons: IconTheme,
private val store: Bookmarks,
private val identities: IdentityManager,
/** A saved bookmark changed, for the servers connected with it. */
private val onEdited: (Bookmark) -> Unit,
) {
private val shortcuts = BookmarkShortcuts(context, icons)
private val main = Handler(Looper.getMainLooper())
private val _all = MutableStateFlow(store.all().toList())
val all: StateFlow<List<Bookmark>> = _all
/** Picks up bookmarks added or changed elsewhere, such as by an import. */
fun refresh() {
_all.value = store.all().toList()
}
fun find(id: String): Bookmark? = store.find(id)
internal fun startupBookmarks(): List<Bookmark> = store.startupBookmarks()
internal fun add(bookmark: Bookmark) {
store.add(bookmark)
save()
}
/** A bookmark to [address] as typed into the connect form, not yet saved. */
fun newBookmark(address: String, nickname: String, password: String, identityId: String): Bookmark {
val (host, port) = SessionController.parseAddress(address)
// Only a nickname other than the identity's is the server's own.
val own = nickname.takeIf { it != identities.nicknameFor(identityId) }.orEmpty()
return Bookmark(host, host, port, own, password).also { it.identityId = identityId }
}
/** Puts [edited] in place of the bookmark at [index], or adds it when [index] is -1. */
fun save(index: Int, edited: Bookmark) {
val all = store.all()
if (index !in all.indices) {
store.add(edited)
} else {
// The icon may have been learnt meanwhile, and belongs to the server, not to the bookmark.
edited.iconId = all[index].takeIf { it.pointsAt(edited.address, edited.port) }?.iconId ?: 0
all[index] = edited
}
save()
onEdited(edited)
}
fun remove(bookmark: Bookmark) {
val index = store.all().indexOf(bookmark)
if (index < 0) return
store.remove(index)
save()
}
/** Bookmarks leading to [address]:[port] take on the icon the server shows now. */
internal fun serverIconChanged(address: String, port: Int, iconId: Long) {
main.post {
val all = store.all()
var changed = false
for (i in all.indices) {
val b = all[i]
if (!b.pointsAt(address, port) || b.iconId == iconId) continue
// A new entry, so the list the UI holds changes along with it.
all[i] = b.copy().also { it.iconId = iconId }
changed = true
}
if (changed) save()
}
}
private fun save() {
store.save()
refresh()
shortcuts.sync(_all.value)
}
val canPinShortcuts: Boolean get() = shortcuts.supported
/** Asks the launcher for a home-screen shortcut connecting to [bookmark]. */
fun pinShortcut(bookmark: Bookmark) {
// A bookmark not saved since ids came in has a new one on every load until it is.
store.save()
shortcuts.pin(bookmark)
}
}
@@ -1,16 +1,11 @@
package eu.lixko.ts3j.client.android package eu.lixko.ts3j.client.android
import androidx.compose.runtime.Immutable import androidx.compose.runtime.Immutable
import eu.lixko.ts3j.client.chat.ChatKey
import eu.lixko.ts3j.client.chat.ChatScope
import eu.lixko.ts3j.client.text.HtmlText import eu.lixko.ts3j.client.text.HtmlText
import eu.lixko.ts3j.client.text.TextQuery import eu.lixko.ts3j.client.text.TextQuery
/** Which conversation a chat line belongs to. */
sealed interface ChatKey {
data object Server : ChatKey
data object Channel : ChatKey
data class Private(val clientId: Int) : ChatKey
}
/** One entry of a chat, as HTML in the form [eu.lixko.ts3j.client.text.ChatHtml] writes. */ /** One entry of a chat, as HTML in the form [eu.lixko.ts3j.client.text.ChatHtml] writes. */
@Immutable @Immutable
data class ChatLine(val id: Long, val html: String) { data class ChatLine(val id: Long, val html: String) {
@@ -31,25 +26,25 @@ data class Conversation(
/** Every conversation of the session: the server's, the channel's, then the private ones. */ /** Every conversation of the session: the server's, the channel's, then the private ones. */
@Immutable @Immutable
data class Chats( data class Chats(
val server: Conversation = Conversation(ChatKey.Server, "Server"), val server: Conversation = Conversation(ChatKey.SERVER, "Server"),
val channel: Conversation = Conversation(ChatKey.Channel, "Channel"), val channel: Conversation = Conversation(ChatKey.CHANNEL, "Channel"),
val private: List<Conversation> = emptyList(), val private: List<Conversation> = emptyList(),
) { ) {
val all: List<Conversation> get() = listOf(server, channel) + private val all: List<Conversation> get() = listOf(server, channel) + private
val anyUnread: Boolean get() = all.any { it.unread } val anyUnread: Boolean get() = all.any { it.unread }
operator fun get(key: ChatKey): Conversation? = when (key) { operator fun get(key: ChatKey): Conversation? = when (key.scope()) {
ChatKey.Server -> server ChatScope.SERVER -> server
ChatKey.Channel -> channel ChatScope.CHANNEL -> channel
is ChatKey.Private -> private.firstOrNull { it.key == key } ChatScope.PRIVATE -> private.firstOrNull { it.key == key }
} }
/** Applies [change] to a conversation, opening a private one titled [title] if needed. */ /** Applies [change] to a conversation, opening a private one titled [title] if needed. */
fun update(key: ChatKey, title: String = "", change: (Conversation) -> Conversation): Chats = when (key) { fun update(key: ChatKey, title: String = "", change: (Conversation) -> Conversation): Chats = when (key.scope()) {
ChatKey.Server -> copy(server = change(server)) ChatScope.SERVER -> copy(server = change(server))
ChatKey.Channel -> copy(channel = change(channel)) ChatScope.CHANNEL -> copy(channel = change(channel))
is ChatKey.Private -> { ChatScope.PRIVATE -> {
val existing = private.indexOfFirst { it.key == key } val existing = private.indexOfFirst { it.key == key }
if (existing < 0) { if (existing < 0) {
copy(private = private + change(Conversation(key, title))) copy(private = private + change(Conversation(key, title)))
@@ -59,7 +54,7 @@ data class Chats(
} }
} }
fun close(key: ChatKey.Private): Chats = copy(private = private.filter { it.key != key }) fun close(key: ChatKey): Chats = copy(private = private.filter { it.key != key })
companion object { companion object {
/** As many lines as a log history loads; older ones leave the conversation. */ /** As many lines as a log history loads; older ones leave the conversation. */
@@ -39,6 +39,8 @@ import kotlin.math.roundToInt
class ConnectionService : LifecycleService() { class ConnectionService : LifecycleService() {
private lateinit var sessions: SessionController private lateinit var sessions: SessionController
private lateinit var icons: IconTheme
private lateinit var audio: AudioSetup
private lateinit var wifiLock: WifiManager.WifiLock private lateinit var wifiLock: WifiManager.WifiLock
private lateinit var wifiBackgroundLock: WifiManager.WifiLock private lateinit var wifiBackgroundLock: WifiManager.WifiLock
private lateinit var wakeLock: PowerManager.WakeLock private lateinit var wakeLock: PowerManager.WakeLock
@@ -48,7 +50,10 @@ class ConnectionService : LifecycleService() {
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
sessions = (application as Ts3Application).sessions val parts = (application as Ts3Application).parts
sessions = parts.sessions
icons = parts.icons
audio = parts.audio
getSystemService(NotificationManager::class.java).createNotificationChannel( getSystemService(NotificationManager::class.java).createNotificationChannel(
NotificationChannel(CHANNEL, getString(R.string.connection_channel), NotificationManager.IMPORTANCE_LOW) NotificationChannel(CHANNEL, getString(R.string.connection_channel), NotificationManager.IMPORTANCE_LOW)
) )
@@ -89,15 +94,15 @@ class ConnectionService : LifecycleService() {
} }
} }
lifecycleScope.launch { lifecycleScope.launch {
sessions.icons.active.drop(1).collect { shown?.let { show(it.state.value, sessions.micOwner.value != null) } } icons.active.drop(1).collect { shown?.let { show(it.state.value, sessions.micOwner.value != null) } }
} }
overlay = PttOverlay(this, sessions.icons, sessions::setPushToTalk) overlay = PttOverlay(this, icons, sessions::setPushToTalk)
lifecycleScope.launch { lifecycleScope.launch {
val owner = sessions.micOwner.flatMapLatest { server -> val owner = sessions.micOwner.flatMapLatest { server ->
server?.let { combine(it.state, it.tree) { state, tree -> state to tree } } ?: flowOf(null) server?.let { combine(it.state, it.tree) { state, tree -> state to tree } } ?: flowOf(null)
} }
combine(owner, sessions.onScreen, sessions.pttOverlay) { held, onScreen, enabled -> combine(owner, sessions.onScreen, audio.pttOverlay) { held, onScreen, enabled ->
val (state, tree) = held ?: return@combine null val (state, tree) = held ?: return@combine null
val wanted = enabled && !onScreen && state.connected && state.micActive && val wanted = enabled && !onScreen && state.connected && state.micActive &&
state.inputMode == Settings.InputMode.PUSH_TO_TALK state.inputMode == Settings.InputMode.PUSH_TO_TALK
@@ -203,7 +208,7 @@ class ConnectionService : LifecycleService() {
private fun statusIcon(self: SelfState): Icon { private fun statusIcon(self: SelfState): Icon {
val key = self.iconKey() ?: return Icon.createWithResource(this, android.R.drawable.ic_btn_speak_now) val key = self.iconKey() ?: return Icon.createWithResource(this, android.R.drawable.ic_btn_speak_now)
val size = (STATUS_ICON_DP * resources.displayMetrics.density).roundToInt() val size = (STATUS_ICON_DP * resources.displayMetrics.density).roundToInt()
val bitmap = sessions.icons.renderMaterial(key, size, Color.WHITE) val bitmap = icons.renderMaterial(key, size, Color.WHITE)
?: return Icon.createWithResource(this, android.R.drawable.ic_btn_speak_now) ?: return Icon.createWithResource(this, android.R.drawable.ic_btn_speak_now)
return Icon.createWithBitmap(bitmap) return Icon.createWithBitmap(bitmap)
} }
@@ -212,7 +217,7 @@ class ConnectionService : LifecycleService() {
private fun largeIcon(self: SelfState): Icon? { private fun largeIcon(self: SelfState): Icon? {
val key = self.iconKey() ?: return null val key = self.iconKey() ?: return null
val size = (LARGE_ICON_DP * resources.displayMetrics.density).roundToInt() val size = (LARGE_ICON_DP * resources.displayMetrics.density).roundToInt()
return sessions.icons.render(listOf(key), size, getColor(android.R.color.system_neutral1_500)) return icons.render(listOf(key), size, getColor(android.R.color.system_neutral1_500))
?.let(Icon::createWithBitmap) ?.let(Icon::createWithBitmap)
} }
@@ -0,0 +1,53 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import android.net.Uri
import eu.lixko.ts3j.client.config.Settings
import eu.lixko.ts3j.client.contacts.Contact
import eu.lixko.ts3j.client.contacts.ContactDefaults
import eu.lixko.ts3j.client.contacts.ContactStore
import eu.lixko.ts3j.client.teamspeak.TeamSpeakSettingsDb
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.withContext
/** The contacts: friends, blocked clients and how each is treated. */
class ContactManager internal constructor(
private val context: Context,
internal val store: ContactStore,
private val settings: Settings,
) {
/** Copies of the contacts, as the store's own entries change in place. */
private val _all = MutableStateFlow(copies())
val all: StateFlow<List<Contact>> = _all
init {
// Mutations report on whichever thread made them, a connection thread included.
store.addListener { _all.value = copies() }
}
private fun copies(): List<Contact> = store.all().map { it.copy() }
/** A copy of the contact to edit and hand back to [save]. */
fun find(uniqueId: String): Contact? = store.find(uniqueId)?.copy()
fun save(contact: Contact) = store.put(contact)
fun remove(uniqueId: String) = store.remove(uniqueId)
/** What a new contact starts with; changed in place, then [saveDefaults]. */
val defaults: ContactDefaults get() = settings.contactDefaults
fun saveDefaults() = settings.save()
/**
* Adds the contacts of a TeamSpeak 3 `settings.db`, overwriting entries for the same clients.
*
* @return how many contacts the file held and how many of them were new
*/
suspend fun import(uri: Uri): Pair<Int, Int> = withContext(Dispatchers.IO) {
val found = withLocalCopy(context, uri, TeamSpeakSettingsDb::readContacts)
found.size to if (found.isEmpty()) 0 else store.merge(found)
}
}
@@ -3,7 +3,7 @@ package eu.lixko.ts3j.client.android
import android.content.Context import android.content.Context
import android.net.Uri import android.net.Uri
import android.provider.OpenableColumns import android.provider.OpenableColumns
import eu.lixko.ts3j.client.net.TeamspeakConnection import eu.lixko.ts3j.client.net.ChannelFiles
import eu.lixko.ts3j.client.net.filetransfer.FileTransfer import eu.lixko.ts3j.client.net.filetransfer.FileTransfer
import eu.lixko.ts3j.client.net.filetransfer.RemoteFile import eu.lixko.ts3j.client.net.filetransfer.RemoteFile
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
@@ -37,7 +37,7 @@ data class TransferRow(
* as the core reads and writes plain files: a download is copied where the user picked once * as the core reads and writes plain files: a download is copied where the user picked once
* complete, an upload is copied out of the picked document first. They outlive the browser page. * complete, an upload is copied out of the picked document first. They outlive the browser page.
*/ */
class FileTransfers internal constructor(private val context: Context, private val conn: () -> TeamspeakConnection) { class FileTransfers internal constructor(private val context: Context, private val files: ChannelFiles) {
private val ids = AtomicLong() private val ids = AtomicLong()
private val handles = HashMap<Long, FileTransfer>() private val handles = HashMap<Long, FileTransfer>()
@@ -52,7 +52,7 @@ class FileTransfers internal constructor(private val context: Context, private v
start(row, temp, onComplete = { start(row, temp, onComplete = {
context.contentResolver.openOutputStream(target)?.use { out -> temp.inputStream().use { it.copyTo(out) } } context.contentResolver.openOutputStream(target)?.use { out -> temp.inputStream().use { it.copyTo(out) } }
?: throw IOException("Could not write the file") ?: throw IOException("Could not write the file")
}) { listener -> conn().downloadFile(channelId, password, file.fullPath, temp, listener) } }) { listener -> files.download(channelId, password, file.fullPath, temp, listener) }
} }
/** Uploads the document at [source] into [directory] (ending in "/"), replacing a file of the same name. */ /** Uploads the document at [source] into [directory] (ending in "/"), replacing a file of the same name. */
@@ -60,7 +60,7 @@ class FileTransfers internal constructor(private val context: Context, private v
val (name, temp) = withContext(Dispatchers.IO) { copyIn(source) } val (name, temp) = withContext(Dispatchers.IO) { copyIn(source) }
val row = add(name, upload = true, channelId, directory, temp.length()) val row = add(name, upload = true, channelId, directory, temp.length())
start(row, temp, onComplete = {}) { listener -> start(row, temp, onComplete = {}) { listener ->
conn().uploadFile(channelId, password, directory + name, temp, true, listener) files.upload(channelId, password, directory + name, temp, true, listener)
} }
} }
@@ -43,7 +43,7 @@ class IconTheme(private val context: Context, private val settings: Settings) {
} }
fun select(pack: IconPack) { fun select(pack: IconPack) {
settings.iconPack = pack.id() settings.iconPack.set(pack.id())
settings.save() settings.save()
reload() reload()
} }
@@ -100,7 +100,7 @@ class IconTheme(private val context: Context, private val settings: Settings) {
private fun reload() { private fun reload() {
val packs = IconPacks.findAll(folder, null) val packs = IconPacks.findAll(folder, null)
val active = IconPacks.select(packs, settings.iconPack) ?: material val active = IconPacks.select(packs, settings.iconPack.get()) ?: material
lookupOrder = IconPacks.lookupOrder(active, packs, material) lookupOrder = IconPacks.lookupOrder(active, packs, material)
cache.evictAll() cache.evictAll()
_packs.value = packs _packs.value = packs
@@ -61,7 +61,7 @@ class IdentityManager(
} }
private fun snapshot(): List<IdentityInfo> = store.all().map { private fun snapshot(): List<IdentityInfo> = store.all().map {
IdentityInfo(it.id, it.name, it.uniqueId, it.securityLevel, it.id == settings.defaultIdentityId, IdentityInfo(it.id, it.name, it.uniqueId, it.securityLevel, it.id == settings.defaultIdentityId.get(),
it.nickname, it.phoneticNickname) it.nickname, it.phoneticNickname)
} }
@@ -93,9 +93,9 @@ class IdentityManager(
/** Makes [entry], or else the first identity, the default while there is none. */ /** Makes [entry], or else the first identity, the default while there is none. */
private fun adoptDefault(entry: IdentityEntry?) { private fun adoptDefault(entry: IdentityEntry?) {
if (store.byId(settings.defaultIdentityId) != null) return if (store.byId(settings.defaultIdentityId.get()) != null) return
val fallback = entry ?: store.all().firstOrNull() ?: return val fallback = entry ?: store.all().firstOrNull() ?: return
settings.defaultIdentityId = fallback.id settings.defaultIdentityId.set(fallback.id)
settings.save() settings.save()
} }
@@ -124,10 +124,13 @@ class IdentityManager(
/** The nickname of the identity a connect with [id] uses; empty when it has none. */ /** The nickname of the identity a connect with [id] uses; empty when it has none. */
fun nicknameOf(id: String): String = fun nicknameOf(id: String): String =
(store.byId(id) ?: store.byId(settings.defaultIdentityId))?.nickname.orEmpty() (store.byId(id) ?: store.byId(settings.defaultIdentityId.get()))?.nickname.orEmpty()
/** The nickname a connect with [id] goes by: the identity's own, else the global one. */
fun nicknameFor(id: String): String = nicknameOf(id).ifBlank { settings.nickname.get() }
fun setDefault(id: String) { fun setDefault(id: String) {
settings.defaultIdentityId = id settings.defaultIdentityId.set(id)
settings.save() settings.save()
refresh() refresh()
} }
@@ -90,6 +90,8 @@ class LevelMonitor(private val settings: Settings, private val audio: AudioBacke
} }
/** Push-to-talk would never open without the button, and the test is there to tune the gate. */ /** Push-to-talk would never open without the button, and the test is there to tune the gate. */
private fun testMode() = private fun testMode(): Settings.InputMode {
if (settings.inputMode == Settings.InputMode.PUSH_TO_TALK) Settings.InputMode.VOICE_ACTIVATION else settings.inputMode val mode = settings.inputMode.get()
return if (mode == Settings.InputMode.PUSH_TO_TALK) Settings.InputMode.VOICE_ACTIVATION else mode
}
} }
@@ -18,7 +18,7 @@ class MainActivity : ComponentActivity() {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
if (savedInstanceState == null) sessions.connectStartupBookmarks(handle(intent)) if (savedInstanceState == null) sessions.connectStartupBookmarks(handle(intent))
setContent { setContent {
Ts3Theme { App(sessions) } Ts3Theme { App((application as Ts3Application).parts) }
} }
} }
@@ -0,0 +1,143 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import android.net.Uri
import android.provider.OpenableColumns
import eu.lixko.ts3j.client.myts.ChatAttachment
import eu.lixko.ts3j.client.myts.ChatAttachments
import eu.lixko.ts3j.client.myts.MyTeamSpeak
import eu.lixko.ts3j.client.myts.MyTeamSpeakLogin
import eu.lixko.ts3j.client.myts.MyTeamSpeakSync
import eu.lixko.ts3j.client.config.Bookmarks
import eu.lixko.ts3j.client.config.IdentityStore
import eu.lixko.ts3j.client.config.Settings
import eu.lixko.ts3j.client.teamspeak.SyncItem
import eu.lixko.ts3j.client.teamspeak.TeamSpeakImporter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.withContext
import java.io.IOException
import java.io.InputStream
/** A file to share in chat, open for reading. */
internal class SharedFile(val name: String, val size: Long, val data: InputStream)
/**
* The myTeamSpeak account the app stays signed in to: what it syncs, and the files shared
* in chat, which are kept in its cloud storage. Its reads block, so they run on [Dispatchers.IO].
*/
class MyTeamSpeakAccount internal constructor(
private val context: Context,
private val pictures: WebPictures,
private val importer: TeamSpeakImporter,
private val bookmarks: BookmarkManager,
private val identities: IdentityManager,
identityStore: IdentityStore,
bookmarkStore: Bookmarks,
settings: Settings,
/** Signed in or out, for the servers to pass on. */
private val onSignInChanged: () -> Unit,
) {
val login: MyTeamSpeakLogin = MyTeamSpeakLogin.load()
private val _signedIn = MutableStateFlow(login.isSignedIn)
val signedIn: StateFlow<Boolean> = _signedIn
private val sync = MyTeamSpeakSync(login, identityStore, bookmarkStore, settings)
/** Files shared in chat. */
internal val attachments = ChatAttachments(login).also {
pictures.addSource(ChatAttachment.SCHEME, it::fetchPicture)
}
suspend fun signIn(email: String, password: String): MyTeamSpeak.Account =
withContext(Dispatchers.IO) { login.signIn(email, password) }
.also {
_signedIn.value = true
onSignInChanged()
// Shared pictures that could not be had signed out.
pictures.retryFailed()
}
suspend fun fetch(): MyTeamSpeak.Account =
try {
withContext(Dispatchers.IO) { login.fetch() }
} finally {
// A sign-in the server no longer takes has signed out.
_signedIn.value = login.isSignedIn
}
suspend fun signOut() {
login.signOut()
_signedIn.value = false
onSignInChanged()
withContext(Dispatchers.IO) { attachments.close() }
}
fun isImported(item: SyncItem): Boolean = importer.isPresent(item)
/** Imports [chosen] out of the account's [all] items, with the identities the chosen bookmarks use; contacts announce themselves. */
suspend fun import(all: List<SyncItem>, chosen: List<SyncItem>): TeamSpeakImporter.Result =
withContext(Dispatchers.IO) { importer.importSelected(all, chosen) }
.also {
bookmarks.refresh()
identities.refresh()
}
/**
* Reads what changed in the account and works out what goes which way. Call on the main
* thread, which owns the bookmarks and identities; the network part runs on [Dispatchers.IO].
*/
suspend fun planSync(): MyTeamSpeakSync.Plan =
try {
sync.plan(withContext(Dispatchers.IO) { sync.fetch() })
} finally {
_signedIn.value = login.isSignedIn
}
/** Sends this side's changes, then brings the account's here; [plan]'s conflicts settled. Main thread. */
suspend fun finishSync(plan: MyTeamSpeakSync.Plan): MyTeamSpeakSync.Result {
try {
withContext(Dispatchers.IO) { sync.upload(plan) }
} finally {
_signedIn.value = login.isSignedIn
}
return sync.apply(plan).also {
bookmarks.refresh()
identities.refresh()
}
}
/** Fetches a file shared in chat whole. */
suspend fun downloadAttachment(ref: ChatAttachment.Ref): ByteArray =
withContext(Dispatchers.IO) { attachments.download(ref, ChatAttachments.MAX_UPLOAD_BYTES) }
/** Fetches a file shared in chat into [uri], e.g. one the user picked to save it as. */
suspend fun saveAttachment(ref: ChatAttachment.Ref, uri: Uri) {
val data = downloadAttachment(ref)
withContext(Dispatchers.IO) {
val out = context.contentResolver.openOutputStream(uri) ?: throw IOException("Could not write the file")
out.use { it.write(data) }
}
}
/** A file picked to share in chat, or why it cannot be. */
internal suspend fun openShared(uri: Uri): Result<SharedFile> = withContext(Dispatchers.IO) {
runCatching {
val resolver = context.contentResolver
val (name, size) = resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE),
null, null, null)?.use { c ->
if (!c.moveToFirst()) null
else c.getString(0).orEmpty() to (if (c.isNull(1)) -1L else c.getLong(1))
} ?: ("" to -1L)
when {
size < 0 -> throw IOException("Could not read the file's size")
size > ChatAttachments.MAX_UPLOAD_BYTES ->
throw IOException("Files over ${ChatAttachments.MAX_UPLOAD_BYTES shr 20} MB cannot be shared")
}
val data = resolver.openInputStream(uri) ?: throw IOException("Could not read the file")
SharedFile(name.ifBlank { uri.lastPathSegment ?: "file" }, size, data)
}
}
}
@@ -144,7 +144,7 @@ class NetworkFollower(context: Context) {
try { try {
val back = withTimeoutOrNull(GIVE_UP_MS) { val back = withTimeoutOrNull(GIVE_UP_MS) {
system(if (connectivity.activeNetwork == null) "Network lost." else "Network changed, reconnecting…") system(if (connectivity.activeNetwork == null) "Network lost." else "Network changed, reconnecting…")
if (session.isBusy) session.connection().disconnectBlocking("Network changed") session.disconnectNow("Network changed")
var retry = RETRY_MS var retry = RETRY_MS
while (true) { while (true) {
val current = awaitNetwork() val current = awaitNetwork()
@@ -156,13 +156,13 @@ class NetworkFollower(context: Context) {
val connected = done.await() val connected = done.await()
attempt = null attempt = null
if (connected) break if (connected) break
if (session.connection().connectErrorId == ERROR_BANNED) break if (session.connectErrorId() == ERROR_BANNED) break
show("Reconnecting, retrying soon…") show("Reconnecting, retrying soon…")
delay(retry) delay(retry)
retry = (retry * 2).coerceAtMost(MAX_RETRY_MS) retry = (retry * 2).coerceAtMost(MAX_RETRY_MS)
} }
} }
if (session.connection().connectErrorId == ERROR_BANNED) { if (session.connectErrorId() == ERROR_BANNED) {
wanted = false wanted = false
unbind() unbind()
} else if (back == null) { } else if (back == null) {
@@ -0,0 +1,19 @@
package eu.lixko.ts3j.client.android
import eu.lixko.ts3j.client.net.RequestException
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.future.await
import java.util.concurrent.CompletableFuture
/** A server request's outcome, failing with its [RequestException]. */
internal suspend fun <T> CompletableFuture<T>.result(): Result<T> =
try {
Result.success(await())
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Result.failure(RequestException.of(e))
}
/** The same for a request with no result. */
internal suspend fun CompletableFuture<Void>.done(): Result<Unit> = result().map { }
@@ -1,6 +1,8 @@
package eu.lixko.ts3j.client.android package eu.lixko.ts3j.client.android
import android.net.Uri import android.net.Uri
import eu.lixko.ts3j.client.chat.ChatKey
import eu.lixko.ts3j.client.chat.ChatScope
import eu.lixko.ts3j.client.config.Bookmark import eu.lixko.ts3j.client.config.Bookmark
import eu.lixko.ts3j.client.contacts.ContactType import eu.lixko.ts3j.client.contacts.ContactType
import eu.lixko.ts3j.client.config.WhisperList import eu.lixko.ts3j.client.config.WhisperList
@@ -10,11 +12,12 @@ import eu.lixko.ts3j.client.net.ChannelSettings
import eu.lixko.ts3j.client.net.ConnectionStats import eu.lixko.ts3j.client.net.ConnectionStats
import eu.lixko.ts3j.client.net.Details import eu.lixko.ts3j.client.net.Details
import eu.lixko.ts3j.client.net.GroupChoice import eu.lixko.ts3j.client.net.GroupChoice
import eu.lixko.ts3j.client.net.Permissions
import eu.lixko.ts3j.client.net.RequestException
import eu.lixko.ts3j.client.net.Whisper import eu.lixko.ts3j.client.net.Whisper
import eu.lixko.ts3j.client.net.ban.BanEntry import eu.lixko.ts3j.client.net.ban.BanEntry
import eu.lixko.ts3j.client.net.ban.BanRule import eu.lixko.ts3j.client.net.ban.BanRule
import eu.lixko.ts3j.client.net.filetransfer.RemoteFile import eu.lixko.ts3j.client.net.filetransfer.RemoteFile
import eu.lixko.ts3j.client.net.ConnectionListener.ChatScope
import eu.lixko.ts3j.client.session.ServerLink import eu.lixko.ts3j.client.session.ServerLink
import eu.lixko.ts3j.client.session.ServerSession import eu.lixko.ts3j.client.session.ServerSession
import eu.lixko.ts3j.client.text.ChatHtml import eu.lixko.ts3j.client.text.ChatHtml
@@ -41,13 +44,12 @@ import kotlin.coroutines.suspendCoroutine
class ServerController internal constructor( class ServerController internal constructor(
/** Unique among the servers of this process run. */ /** Unique among the servers of this process run. */
val id: Int, val id: Int,
private val parts: ServerParts,
/** The owner, told of what happens to this server. */
private val app: SessionController, private val app: SessionController,
) { ) {
internal val session = ServerSession( internal val session = parts.session(Listener())
app.settings, app.identityStore, app.audio, app.sounds, app.contactStore, Listener() private val network = parts.network.follow(session, ::refresh, ::system)
)
internal val conn get() = session.connection()
private val network = app.network.follow(session, ::refresh, ::system)
/** Whether this server holds the microphone; set by [SessionController] as it moves. */ /** Whether this server holds the microphone; set by [SessionController] as it moves. */
@Volatile @Volatile
@@ -80,18 +82,18 @@ class ServerController internal constructor(
set(value) { set(value) {
field = value field = value
if (value != null) markRead(value) if (value != null) markRead(value)
if (value is ChatKey.Private) app.notifier.clear(id, value.clientId) if (value != null && value.isPrivate) parts.notifier.clear(id, value.clientId())
} }
/** Counts the answers to info requests, for the details on screen to be read again. */ /** Counts the answers to info requests, for the details on screen to be read again. */
private val _infoUpdates = MutableStateFlow(0) private val _infoUpdates = MutableStateFlow(0)
val infoUpdates: StateFlow<Int> = _infoUpdates val infoUpdates: StateFlow<Int> = _infoUpdates
val images = ServerImages(conn) val images = ServerImages(session.icons(), session.avatars())
/** A private chat a notification asked to show, until the UI took it up. */ /** A private chat a notification asked to show, until the UI took it up. */
private val _chatRequest = MutableStateFlow<ChatKey.Private?>(null) private val _chatRequest = MutableStateFlow<ChatKey?>(null)
val chatRequest: StateFlow<ChatKey.Private?> = _chatRequest val chatRequest: StateFlow<ChatKey?> = _chatRequest
private val lineIds = AtomicLong() private val lineIds = AtomicLong()
@@ -103,8 +105,8 @@ class ServerController internal constructor(
val isConnected: Boolean get() = session.isConnected val isConnected: Boolean get() = session.isConnected
internal val isBusy: Boolean get() = session.isBusy || network.isRecovering internal val isBusy: Boolean get() = session.isBusy || network.isRecovering
internal val microphone get() = if (session.isConnected) conn.microphone else null internal val microphone get() = if (session.isConnected) session.microphone() else null
internal val playback get() = if (session.isConnected) conn.playback else null internal val playback get() = if (session.isConnected) session.playback() else null
/** Not on the server and not trying to get back on it: done with. */ /** Not on the server and not trying to get back on it: done with. */
internal val ended: Boolean get() = started && !isBusy internal val ended: Boolean get() = started && !isBusy
@@ -126,8 +128,27 @@ class ServerController internal constructor(
refresh() refresh()
} }
/** The bookmark this server was connected from, if any. */
@Volatile
private var bookmarkId: String? = null
@Volatile
private var whisperControls = false
internal fun applyBookmark(bookmark: Bookmark) {
bookmarkId = bookmark.id
whisperControls = bookmark.showWhisperControls
refresh()
}
/** Takes on an edit of the bookmark we connected from, without reconnecting. */
internal fun bookmarkEdited(bookmark: Bookmark) {
if (bookmark.id == bookmarkId) applyBookmark(bookmark)
}
/** A bookmark leading back to this server, joining [channelId]; not yet saved. */ /** A bookmark leading back to this server, joining [channelId]; not yet saved. */
fun bookmark(channelId: Int): Bookmark? = session.toBookmark(conn.model.channelPath(channelId)) fun bookmark(channelId: Int): Bookmark? = session.toBookmark(session.model().channelPath(channelId))
?.also { it.showWhisperControls = whisperControls }
fun disconnect() { fun disconnect() {
left = true left = true
@@ -155,14 +176,18 @@ class ServerController internal constructor(
fun setAway(away: Boolean) = session.setAway(away, null) fun setAway(away: Boolean) = session.setAway(away, null)
/** Asks for talk power giving [reason], or withdraws the request with null. */
fun setTalkRequest(reason: String?) =
if (reason == null) session.cancelTalkRequest() else session.requestTalkPower(reason)
// ---- channels and clients ---- // ---- channels and clients ----
fun joinChannel(channelId: Int, password: String? = null) { fun joinChannel(channelId: Int, password: String? = null) {
if (session.isConnected) conn.joinChannel(channelId, password) if (session.isConnected) session.channels().join(channelId, password)
} }
fun setSubscribed(channelId: Int, subscribed: Boolean) { fun setSubscribed(channelId: Int, subscribed: Boolean) {
if (session.isConnected) conn.setChannelsSubscribed(listOf(channelId), subscribed) if (session.isConnected) session.channels().setSubscribed(listOf(channelId), subscribed)
} }
fun toggleCollapsed(channelId: Int) = fun toggleCollapsed(channelId: Int) =
@@ -170,178 +195,158 @@ class ServerController internal constructor(
fun expand(channelIds: Collection<Int>) = _collapsed.update { it - channelIds.toSet() } fun expand(channelIds: Collection<Int>) = _collapsed.update { it - channelIds.toSet() }
val canMoveClients: Boolean get() = session.canMoveClients() /** What we may do on this server; nothing while not connected. */
val permissions: Permissions get() = session.permissions()
fun moveClient(clientId: Int, channelId: Int) { /** The channel kicked clients go back to; 0 until the server named it. */
if (session.isConnected) conn.moveClient(clientId, channelId, null) val defaultChannelId: Int get() = session.model().defaultChannelId()
fun moveClients(clientIds: Collection<Int>, channelId: Int) {
if (session.isConnected) session.clients().move(clientIds, channelId)
} }
fun poke(clientId: Int, message: String) { fun poke(clientId: Int, message: String) {
if (session.isConnected) conn.poke(clientId, message) if (session.isConnected) session.clients().poke(clientId, message)
} }
/** The client's playback volume change in dB; 0 when unchanged. */ /** The client's playback volume change in dB; 0 when unchanged. */
fun clientVolume(clientId: Int): Double = fun clientVolume(clientId: Int): Double =
conn.model.getClient(clientId)?.let { conn.getClientVolumeModifier(it) } ?: 0.0 session.model().getClient(clientId)?.let { session.contacts().volumeModifier(it) } ?: 0.0
fun setClientVolume(clientId: Int, decibels: Double) { fun setClientVolume(clientId: Int, decibels: Double) {
conn.model.getClient(clientId)?.let { conn.setClientVolumeModifier(it, decibels) } session.model().getClient(clientId)?.let { session.contacts().setVolumeModifier(it, decibels) }
} }
// ---- whisper ---- // ---- whisper ----
fun setWhisper(whisper: Whisper?) = session.setWhisper(whisper) fun setWhisper(whisper: Whisper?) = session.setWhisper(whisper)
fun whisperToChannel(channelId: Int) = conn.model.getChannel(channelId)?.let { setWhisper(Whisper.toChannel(it)) } fun whisperToChannel(channelId: Int) = session.model().getChannel(channelId)?.let { setWhisper(Whisper.toChannel(it)) }
fun whisperToClient(clientId: Int) = conn.model.getClient(clientId)?.let { setWhisper(Whisper.toClient(it)) } fun whisperToClient(clientId: Int) = session.model().getClient(clientId)?.let { setWhisper(Whisper.toClient(it)) }
/** The client who whispered to us last, while on the server. */ /** The client who whispered to us last, while on the server. */
fun lastWhisperer(): ClientEntry? = session.lastWhisperer() fun lastWhisperer(): ClientEntry? = session.lastWhisperer()
/** A channel as a whisper list holds it: by path, so the list works on any server with that channel. */ /** A channel as a whisper list holds it: by path, so the list works on any server with that channel. */
fun channelRef(channelId: Int): String? = conn.model.getChannel(channelId)?.let { conn.model.channelPath(it.id) } fun channelRef(channelId: Int): String? = session.model().getChannel(channelId)?.let { session.model().channelPath(it.id) }
fun clientRef(clientId: Int): WhisperList.Client? = fun clientRef(clientId: Int): WhisperList.Client? =
conn.model.getClient(clientId)?.let { WhisperList.Client(it.uniqueId, it.nickname) } session.model().getClient(clientId)?.let { WhisperList.Client(it.uniqueId, it.nickname) }
/** The clients on the server, for adding to a whisper list; ourselves left out. */ /** The clients on the server, for adding to a whisper list; ourselves left out. */
fun clientRefs(): List<WhisperList.Client> = if (!session.isConnected) emptyList() fun clientRefs(): List<WhisperList.Client> = if (!session.isConnected) emptyList()
else conn.model.allClients().filter { it.id != conn.selfClientId && !it.uniqueId.isNullOrEmpty() } else session.model().allClients().filter { it.id != session.selfClientId() && !it.uniqueId.isNullOrEmpty() }
.sortedBy { it.nickname.lowercase() }.map { WhisperList.Client(it.uniqueId, it.nickname) } .sortedBy { it.nickname.lowercase() }.map { WhisperList.Client(it.uniqueId, it.nickname) }
fun channelPaths(): List<String> = session.channelPaths() fun channelPaths(): List<String> = session.channelPaths()
// ---- channel administration ---- // ---- channel administration ----
val canCreateChannels: Boolean get() = session.canCreateChannels()
val canEditChannels: Boolean get() = session.canEditChannels()
val canDeleteChannels: Boolean get() = session.canDeleteChannels()
/** The channels a channel can sort after: its siblings, or [parentId]'s children for a new one. */ /** The channels a channel can sort after: its siblings, or [parentId]'s children for a new one. */
fun sortChoices(channelId: Int, parentId: Int): List<ChannelNode> = fun sortChoices(channelId: Int, parentId: Int): List<ChannelNode> =
if (channelId > 0) conn.model.siblingsOf(channelId) else conn.model.childrenOf(parentId) if (channelId > 0) session.model().siblingsOf(channelId) else session.model().childrenOf(parentId)
/** A channel's editable properties as the server has them. */ /** A channel's editable properties as the server has them. */
suspend fun channelSettings(channelId: Int): Result<ChannelSettings> = suspendCoroutine { done -> suspend fun channelSettings(channelId: Int): Result<ChannelSettings> = session.channels().settings(channelId).result()
conn.requestChannelSettings(channelId) { settings, error ->
done.resume(if (error == null) Result.success(settings) else Result.failure(IllegalStateException(error)))
}
}
/** Each of these answers null once done, else why not. */ suspend fun editChannel(channelId: Int, changes: Map<String, String>): Result<Unit> =
suspend fun editChannel(channelId: Int, changes: Map<String, String>): String? = if (changes.isEmpty()) Result.success(Unit)
if (changes.isEmpty()) null else session.channels().edit(channelId, changes, emptyMap(), emptyList()).done()
else suspendCoroutine { done -> conn.applyChannelEdit(channelId, changes, emptyMap(), emptyList()) { done.resume(it) } }
suspend fun createChannel(parentId: Int, settings: ChannelSettings): String? = suspendCoroutine { done -> suspend fun createChannel(parentId: Int, settings: ChannelSettings): Result<Unit> =
conn.createChannel(parentId, settings.creationParameters(), emptyMap()) { _, error -> done.resume(error) } session.channels().create(parentId, settings.creationParameters(), emptyMap()).result().map { }
}
/** Deletes a channel, with its sub-channels and the clients in it moved out. */ /** Deletes a channel, with its sub-channels and the clients in it moved out. */
suspend fun deleteChannel(channelId: Int): String? = suspend fun deleteChannel(channelId: Int): Result<Unit> = session.channels().delete(channelId, true).done()
suspendCoroutine { done -> conn.deleteChannel(channelId, true) { done.resume(it) } }
// ---- files ---- // ---- files ----
val files = app.fileTransfers { conn } val files = parts.fileTransfers(session.files())
/** The files in a directory of a channel's repository; empty for an empty one. */ /** The files in a directory of a channel's repository; empty for an empty one. */
suspend fun listFiles(channelId: Int, password: String, path: String): Result<List<RemoteFile>> = suspend fun listFiles(channelId: Int, password: String, path: String): Result<List<RemoteFile>> =
withContext(Dispatchers.IO) { runCatching { conn.listFiles(channelId, password, path) } } withContext(Dispatchers.IO) { runCatching { session.files().list(channelId, password, path) } }
/** Each of these answers null once done, else why not. */ suspend fun createDirectory(channelId: Int, password: String, path: String): Result<Unit> =
suspend fun createDirectory(channelId: Int, password: String, path: String): String? = fileCall { session.files().createDirectory(channelId, password, path) }
fileCall { conn.createDirectory(channelId, password, path) }
suspend fun deleteFile(channelId: Int, password: String, path: String): String? = suspend fun deleteFile(channelId: Int, password: String, path: String): Result<Unit> =
fileCall { conn.deleteFile(channelId, password, path) } fileCall { session.files().delete(channelId, password, path) }
suspend fun renameFile(channelId: Int, password: String, from: String, to: String): String? = suspend fun renameFile(channelId: Int, password: String, from: String, to: String): Result<Unit> =
fileCall { conn.renameFile(channelId, password, from, to) } fileCall { session.files().rename(channelId, password, from, to) }
private suspend fun fileCall(call: () -> Unit): String? = withContext(Dispatchers.IO) { private suspend fun fileCall(call: () -> Unit): Result<Unit> = withContext(Dispatchers.IO) { runCatching(call) }
runCatching(call).exceptionOrNull()?.let { it.message ?: it.javaClass.simpleName }
}
// ---- moderation ---- // ---- moderation ----
val canKickFromChannel: Boolean get() = session.canKickFromChannel() val canRequestTalkPower: Boolean get() = session.canRequestTalkPower()
val canKickFromServer: Boolean get() = session.canKickFromServer()
val canBanClients: Boolean get() = session.canBanClients()
val canViewBanList: Boolean get() = session.canViewBanList()
val canCreateBans: Boolean get() = session.isConnected && conn.model.permits("b_client_ban_create")
/** The longest ban we may hand out in seconds; 0 or -1 for no limit. */ fun kickFromChannel(clientIds: Collection<Int>, reason: String) {
val maxBanSeconds: Long get() = conn.model.maxBanSeconds() if (session.isConnected) session.clients().kickFromChannel(clientIds, reason)
fun kickFromChannel(clientId: Int, reason: String) {
if (session.isConnected) conn.kickFromChannel(clientId, reason)
} }
fun kickFromServer(clientId: Int, reason: String) { fun kickFromServer(clientIds: Collection<Int>, reason: String) {
if (session.isConnected) conn.kickFromServer(clientId, reason) if (session.isConnected) session.clients().kickFromServer(clientIds, reason)
}
fun setTalker(clientIds: Collection<Int>, talker: Boolean) {
if (session.isConnected) session.clients().setTalker(clientIds, talker)
} }
/** Bans a client for [seconds], or for good with 0. */ /** Bans a client for [seconds], or for good with 0. */
fun ban(clientId: Int, seconds: Long, reason: String) { fun ban(clientId: Int, seconds: Long, reason: String) {
if (session.isConnected) conn.banClient(clientId, seconds, reason) if (session.isConnected) session.clients().ban(clientId, seconds, reason)
} }
fun serverGroupChoices(clientId: Int): List<GroupChoice> = fun serverGroupChoices(clientId: Int): List<GroupChoice> =
conn.model.getClient(clientId)?.let(conn.model::serverGroupChoices).orEmpty() session.model().getClient(clientId)?.let(session.model()::serverGroupChoices).orEmpty()
fun channelGroupChoices(clientId: Int): List<GroupChoice> = fun channelGroupChoices(clientId: Int): List<GroupChoice> =
conn.model.getClient(clientId)?.let(conn.model::channelGroupChoices).orEmpty() session.model().getClient(clientId)?.let(session.model()::channelGroupChoices).orEmpty()
fun setServerGroup(clientId: Int, groupId: Int, assign: Boolean) { fun setServerGroup(clientId: Int, groupId: Int, assign: Boolean) {
val client = conn.model.getClient(clientId) ?: return val client = session.model().getClient(clientId) ?: return
if (session.isConnected) conn.setClientServerGroup(client.databaseId, groupId, assign) if (session.isConnected) session.clients().setServerGroup(client.databaseId, groupId, assign)
} }
/** Gives a client [groupId] in the channel they are in. */ /** Gives a client [groupId] in the channel they are in. */
fun setChannelGroup(clientId: Int, groupId: Int) { fun setChannelGroup(clientId: Int, groupId: Int) {
val client = conn.model.getClient(clientId) ?: return val client = session.model().getClient(clientId) ?: return
if (session.isConnected) conn.setClientChannelGroup(client.databaseId, client.channelId, groupId) if (session.isConnected) session.clients().setChannelGroup(client.databaseId, client.channelId, groupId)
} }
// ---- ban list ---- // ---- ban list ----
/** The server's bans, or why they could not be read. */
/** One reading of a client's connection figures, or null when not connected. */ /** One reading of a client's connection figures, or null when not connected. */
suspend fun connectionStats(clientId: Int): ConnectionStats? = suspend fun connectionStats(clientId: Int): ConnectionStats? =
if (!session.isConnected) null if (!session.isConnected) null
else suspendCoroutine { done -> conn.requestConnectionInfo(clientId) { done.resume(it) } } else suspendCoroutine { done -> session.requestConnectionInfo(clientId) { done.resume(it) } }
suspend fun banList(): Result<List<BanEntry>> = suspendCoroutine { done -> /** The server's bans, or why they could not be read. */
conn.requestBanList { bans, error -> suspend fun banList(): Result<List<BanEntry>> = session.bans().list().result()
done.resume(if (error == null) Result.success(bans) else Result.failure(IllegalStateException(error)))
}
}
/** Each of these answers null once done, else why not. */ suspend fun addBan(rule: BanRule): Result<Unit> = session.bans().add(rule).done()
suspend fun addBan(rule: BanRule): String? = suspendCoroutine { done -> conn.addBan(rule) { done.resume(it) } }
suspend fun replaceBan(banId: Int, rule: BanRule): String? = suspend fun replaceBan(banId: Int, rule: BanRule): Result<Unit> = session.bans().replace(banId, rule).done()
suspendCoroutine { done -> conn.replaceBan(banId, rule) { done.resume(it) } }
suspend fun deleteBans(banIds: Collection<Int>): String? = suspend fun deleteBans(banIds: Collection<Int>): Result<Unit> = session.bans().delete(banIds).done()
suspendCoroutine { done -> conn.deleteBans(banIds) { done.resume(it) } }
fun canDeleteBans(bans: Collection<BanEntry>): Boolean = conn.model.canDeleteBans(bans, conn.selfUniqueId) fun canDeleteBans(bans: Collection<BanEntry>): Boolean = permissions.canDeleteBans(bans, session.selfUniqueId())
fun canEditBan(ban: BanEntry): Boolean = conn.model.canEditBan(ban, conn.selfUniqueId) fun canEditBan(ban: BanEntry): Boolean = permissions.canEditBan(ban, session.selfUniqueId())
fun isOwnBan(ban: BanEntry): Boolean = ban.createdBy(conn.selfUniqueId) fun isOwnBan(ban: BanEntry): Boolean = ban.createdBy(session.selfUniqueId())
/** Uploads [data] as our avatar; null once it is set, else why not. */ /** Uploads [data] as our avatar. */
suspend fun setAvatar(data: ByteArray): String? { suspend fun setAvatar(data: ByteArray): Result<Unit> {
if (!session.isConnected) return "Not connected" if (!session.isConnected) return Result.failure(RequestException.notConnected())
val file = withContext(Dispatchers.IO) { val file = withContext(Dispatchers.IO) {
File.createTempFile("avatar", null, app.cacheDir).apply { writeBytes(data) } File.createTempFile("avatar", null, parts.cacheDir).apply { writeBytes(data) }
} }
return try { return try {
suspendCoroutine { done -> conn.setAvatar(file) { done.resume(it) } } session.avatarAdmin().set(file).done()
} finally { } finally {
file.delete() file.delete()
} }
@@ -350,78 +355,67 @@ class ServerController internal constructor(
// ---- details ---- // ---- details ----
fun serverDetails(): Details? = fun serverDetails(): Details? =
if (session.isConnected) Details.server(conn.model, "${conn.serverHost}:${conn.serverPort}") else null if (session.isConnected) Details.server(session.model(), "${session.address()}:${session.port()}") else null
fun channelDetails(channelId: Int): Details? = conn.model.getChannel(channelId)?.let(Details::channel) fun channelDetails(channelId: Int): Details? = session.model().getChannel(channelId)?.let(Details::channel)
fun clientDetails(clientId: Int): Details? = conn.model.getClient(clientId)?.let { fun clientDetails(clientId: Int): Details? = session.model().getClient(clientId)?.let {
Details.client(it, conn.model, app.contactStore.find(it.uniqueId)) Details.client(it, session.model(), parts.contactStore.find(it.uniqueId))
} }
/** Asks the server for what the channel's details lack; they change once it answers. */ /** Asks the server for what the channel's details lack; they change once it answers. */
fun requestChannelDetails(channelId: Int) { fun requestChannelDetails(channelId: Int) {
val channel = conn.model.getChannel(channelId) ?: return val channel = session.model().getChannel(channelId) ?: return
if (session.isConnected && !channel.descriptionLoaded) conn.requestChannelInfo(channelId) if (session.isConnected && !channel.descriptionLoaded) session.channels().requestInfo(channelId)
} }
fun requestClientDetails(clientId: Int) { fun requestClientDetails(clientId: Int) {
if (session.isConnected) conn.requestClientInfo(clientId) if (session.isConnected) session.clients().requestInfo(clientId)
} }
/** Files a client on the server as a contact; a new entry takes the type's defaults. */ /** Files a client on the server as a contact; a new entry takes the type's defaults. */
fun addContact(clientId: Int, type: ContactType) { fun addContact(clientId: Int, type: ContactType) {
val client = conn.model.getClient(clientId) ?: return val client = session.model().getClient(clientId) ?: return
app.contactStore.add(client.uniqueId, client.nickname, type, app.settings.contactDefaults) parts.contactStore.add(client.uniqueId, client.nickname, type, parts.settings.contactDefaults)
} }
internal fun contactsChanged() { internal fun contactsChanged() {
treeScope.launch { conn.applyContacts() } treeScope.launch { session.contacts().applyAll() }
scheduleTree(structure = false) scheduleTree(structure = false)
} }
// ---- chat ---- // ---- chat ----
/** Opens the private chat with a client, loading what was said before. */ /** Opens the private chat with a client, loading what was said before. */
fun openPrivateChat(clientId: Int): ChatKey.Private { fun openPrivateChat(clientId: Int): ChatKey {
val key = ChatKey.Private(clientId) val key = ChatKey.privateWith(clientId)
val client = conn.model.getClient(clientId) val client = session.model().getClient(clientId)
if (client != null) { if (client != null) {
_chats.update { chats -> _chats.update { chats ->
chats.update(key, conn.displayName(client)) { it.copy(uniqueId = client.uniqueId) } chats.update(key, session.contacts().displayName(client)) { it.copy(uniqueId = client.uniqueId) }
} }
conn.loadPrivateChatHistory(clientId, client.uniqueId) session.loadPrivateChatHistory(clientId, client.uniqueId)
} }
return key return key
} }
fun closePrivateChat(key: ChatKey.Private) = _chats.update { it.close(key) } fun closePrivateChat(key: ChatKey) = _chats.update { it.close(key) }
fun send(key: ChatKey, text: String) = session.sendChat(scope(key), peer(key), text) fun send(key: ChatKey, text: String) = session.sendChat(key, text)
/** Shares the file at [uri] in a chat, through myTeamSpeak; failures are told in the chat or as errors. */ /** Shares the file at [uri] in a chat, through myTeamSpeak; failures are told in the chat or as errors. */
suspend fun sendFile(key: ChatKey, uri: Uri) { suspend fun sendFile(key: ChatKey, uri: Uri) {
app.openShared(uri) parts.openShared(uri)
.onSuccess { session.sendAttachment(scope(key), peer(key), app.attachments, it.data, it.size, it.name) } .onSuccess { session.sendAttachment(key, parts.attachments, it.data, it.size, it.name) }
.onFailure { app.error(it.message ?: "Could not read the file") } .onFailure { app.error(it.message ?: "Could not read the file") }
} }
private fun scope(key: ChatKey) = when (key) {
ChatKey.Server -> ChatScope.SERVER
ChatKey.Channel -> ChatScope.CHANNEL
is ChatKey.Private -> ChatScope.PRIVATE
}
private fun peer(key: ChatKey) = if (key is ChatKey.Private) key.clientId else 0
/** Where files shared on this server lie; empty before it is known. */
private val room: String get() = conn.serverUniqueId().orEmpty()
fun markRead(key: ChatKey) { fun markRead(key: ChatKey) {
if (_chats.value[key]?.unread == true) _chats.update { chats -> chats.update(key) { it.copy(unread = false) } } if (_chats.value[key]?.unread == true) _chats.update { chats -> chats.update(key) { it.copy(unread = false) } }
} }
internal fun requestChat(clientId: Int) { internal fun requestChat(clientId: Int) {
_chatRequest.value = ChatKey.Private(clientId) _chatRequest.value = ChatKey.privateWith(clientId)
} }
fun chatRequestHandled() { fun chatRequestHandled() {
@@ -430,27 +424,26 @@ class ServerController internal constructor(
/** Answers a private message from its notification. */ /** Answers a private message from its notification. */
internal fun reply(clientId: Int, text: String) { internal fun reply(clientId: Int, text: String) {
if (session.isConnected) send(ChatKey.Private(clientId), text) else app.notifier.clear(id, clientId) if (session.isConnected) send(ChatKey.privateWith(clientId), text) else parts.notifier.clear(id, clientId)
} }
private fun append(key: ChatKey, title: String, html: String) { private fun addLine(key: ChatKey, title: String, html: String) {
if (html.isEmpty()) return
val line = ChatLine(lineIds.incrementAndGet(), html) val line = ChatLine(lineIds.incrementAndGet(), html)
_chats.update { chats -> chats.update(key, title) { it.append(line, read = viewing == key) } } _chats.update { chats -> chats.update(key, title) { it.append(line, read = viewing == key) } }
} }
private fun setHistory(key: ChatKey, title: String, entries: List<String>) { private fun replaceLines(key: ChatKey, title: String, html: List<String>) {
val lines = entries.map { ChatHtml.logEntry(it, room) }.filter { it.isNotEmpty() } val lines = html.map { ChatLine(lineIds.incrementAndGet(), it) }
.map { ChatLine(lineIds.incrementAndGet(), it) }
_chats.update { chats -> chats.update(key, title) { it.copy(lines = lines) } } _chats.update { chats -> chats.update(key, title) { it.copy(lines = lines) } }
} }
private fun system(text: String) = append(ChatKey.Server, "", ChatHtml.system(text)) /** One of this app's own notices, in the server chat. */
private fun system(text: String) = addLine(ChatKey.SERVER, "", ChatHtml.system(text))
// ---- snapshots ---- // ---- snapshots ----
private fun snapshotState(): SessionState { private fun snapshotState(): SessionState {
val self = conn.model.getClient(conn.selfClientId) val self = session.model().getClient(session.selfClientId())
return SessionState( return SessionState(
title = session.title(), title = session.title(),
status = network.status ?: session.status(), status = network.status ?: session.status(),
@@ -461,13 +454,14 @@ class ServerController internal constructor(
micMuted = session.isMicMuted, micMuted = session.isMicMuted,
deafened = session.isDeafened, deafened = session.isDeafened,
away = session.isAway, away = session.isAway,
selfClientId = if (session.isConnected) conn.selfClientId else 0, selfClientId = if (session.isConnected) session.selfClientId() else 0,
channelId = if (session.isConnected) self?.channelId ?: 0 else 0, channelId = if (session.isConnected) self?.channelId ?: 0 else 0,
inputMode = app.settings.inputMode, inputMode = parts.settings.inputMode.get(),
hostButton = if (session.isConnected) conn.model.hostButton() else null, hostButton = if (session.isConnected) session.model().hostButton() else null,
self = session.selfState(), self = session.selfState(),
whisper = session.whisper()?.label, whisper = session.whisper()?.label,
whisperNobody = session.isWhisperingToNobody, whisperNobody = session.isWhisperingToNobody,
whisperControls = whisperControls,
) )
} }
@@ -483,33 +477,36 @@ class ServerController internal constructor(
treeScope.launch { treeScope.launch {
delay(TREE_FRAME_MS) delay(TREE_FRAME_MS)
treePending.set(false) treePending.set(false)
if (structureChanged.getAndSet(false)) roots = conn.model.buildTree() if (structureChanged.getAndSet(false)) roots = session.model().buildTree()
_tree.value = ServerTree.of(roots, conn.model, conn.contacts, app.settings.colorContacts, _tree.value = ServerTree.of(roots, session.model(), session.contacts().store(),
app.settings.countryFlags, app.settings.clientRowColors) parts.settings.colorContacts.get(), parts.settings.countryFlags.get(), parts.settings.clientRowColors)
val serverName = if (session.isConnected) conn.model.serverName.orEmpty() else ""
val channelName = session.currentChannel()?.name.orEmpty()
_chats.update {
it.copy(
server = it.server.copy(title = serverName.ifBlank { "Server" }),
channel = it.channel.copy(title = channelName.ifBlank { "Channel" }),
)
}
refresh() refresh()
} }
} }
private inner class Listener : ServerSession.Listener { private inner class Listener : ServerSession.Listener {
override fun onSessionChanged() = refresh() override fun onSessionChanged() = refresh()
override fun onSystemMessage(text: String) = system(text)
override fun onOwnChat(scope: ChatScope, peerClientId: Int, peerName: String, text: String) { override fun append(key: ChatKey, title: String, html: String) = addLine(key, title, html)
val self = conn.model.getClient(conn.selfClientId)?.nickname ?: app.settings.nickname
val html = ChatHtml.message(conn.selfClientId, conn.selfUniqueId, "$self (you)", text, room) override fun setHistory(key: ChatKey, title: String, html: List<String>) = replaceLines(key, title, html)
append(key(scope, peerClientId), peerName, html)
if (scope == ChatScope.PRIVATE) app.notifier.sent(id, peerClientId, ChatHtml.plainMessage(text)) override fun rename(key: ChatKey, name: String) = _chats.update {
when (key.scope()) {
ChatScope.SERVER -> it.copy(server = it.server.copy(title = name.ifBlank { "Server" }))
ChatScope.CHANNEL -> it.copy(channel = it.channel.copy(title = name.ifBlank { "Channel" }))
else -> it
}
} }
override fun onStatus(status: String) {} override fun closePrivateChats() = _chats.update { it.copy(private = emptyList()) }
override fun onPrivateMessage(fromClientId: Int, fromName: String, message: String) {
if (!app.foreground) parts.notifier.received(id, fromClientId, fromName, ChatHtml.plainMessage(message))
}
override fun onPrivateMessageSent(toClientId: Int, message: String) =
parts.notifier.sent(id, toClientId, ChatHtml.plainMessage(message))
override fun onConnected() { override fun onConnected() {
network.onConnected() network.onConnected()
@@ -519,8 +516,7 @@ class ServerController internal constructor(
override fun onDisconnected(reason: String?) { override fun onDisconnected(reason: String?) {
network.onDisconnected() network.onDisconnected()
app.notifier.clearServer(id) parts.notifier.clearServer(id)
_chats.update { it.copy(private = emptyList()) }
app.disconnected(this@ServerController) app.disconnected(this@ServerController)
scheduleTree(structure = true) scheduleTree(structure = true)
refresh() refresh()
@@ -529,7 +525,7 @@ class ServerController internal constructor(
override fun onModelChanged() { override fun onModelChanged() {
scheduleTree(structure = true) scheduleTree(structure = true)
// A server edit may have changed it. // A server edit may have changed it.
if (session.isConnected && conn.model.hostButton() != _state.value.hostButton) refresh() if (session.isConnected && session.model().hostButton() != _state.value.hostButton) refresh()
} }
override fun onServerIconChanged(iconId: Long) = override fun onServerIconChanged(iconId: Long) =
@@ -543,38 +539,16 @@ class ServerController internal constructor(
override fun onIconsUpdated() = images.loaded() override fun onIconsUpdated() = images.loaded()
override fun onChat(scope: ChatScope, fromClientId: Int, fromUniqueId: String?, fromName: String, message: String) {
append(key(scope, fromClientId), fromName, ChatHtml.message(fromClientId, fromUniqueId, fromName, message, room))
if (scope == ChatScope.PRIVATE && !app.foreground) {
app.notifier.received(id, fromClientId, fromName, ChatHtml.plainMessage(message))
}
}
override fun onChatHistory(scope: ChatScope, htmlEntries: List<String>) {
if (scope != ChatScope.PRIVATE) setHistory(key(scope, 0), "", htmlEntries)
}
override fun onPrivateChatHistory(clientId: Int, nickname: String, htmlEntries: List<String>) =
setHistory(ChatKey.Private(clientId), nickname, htmlEntries)
override fun onTalkStateChanged(clientId: Int, talking: Boolean) { override fun onTalkStateChanged(clientId: Int, talking: Boolean) {
if (clientId == conn.selfClientId && micOwner) app.talking(talking) if (clientId == session.selfClientId() && micOwner) app.talking(talking)
scheduleTree(structure = false) scheduleTree(structure = false)
} }
override fun onError(message: String) = app.error(message) override fun onError(message: String) = app.error(message)
override fun onPoke(fromName: String, message: String) = app.poked(fromName, message) override fun onPoke(fromName: String, message: String) = app.poked(fromName, message)
override fun onServerLog(message: String) = append(ChatKey.Server, "", ChatHtml.serverLog(message))
override fun onServerLogHtml(html: String) = append(ChatKey.Server, "", ChatHtml.logEntry(html, room))
} }
private fun key(scope: ChatScope, peerClientId: Int): ChatKey = when (scope) {
ChatScope.SERVER -> ChatKey.Server
ChatScope.CHANNEL -> ChatKey.Channel
ChatScope.PRIVATE -> ChatKey.Private(peerClientId)
}
private companion object { private companion object {
const val TREE_FRAME_MS = 30L const val TREE_FRAME_MS = 30L
@@ -3,7 +3,8 @@ package eu.lixko.ts3j.client.android
import android.graphics.BitmapFactory import android.graphics.BitmapFactory
import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.asImageBitmap
import eu.lixko.ts3j.client.net.TeamspeakConnection import eu.lixko.ts3j.client.net.IconRepository
import eu.lixko.ts3j.client.net.avatar.AvatarRepository
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update import kotlinx.coroutines.flow.update
@@ -13,7 +14,10 @@ import java.util.concurrent.ConcurrentHashMap
* One server's icons and its clients' avatars, decoded once. What is still * One server's icons and its clients' avatars, decoded once. What is still
* downloading reads as null until [version] moves on. * downloading reads as null until [version] moves on.
*/ */
class ServerImages internal constructor(private val conn: TeamspeakConnection) { class ServerImages internal constructor(
private val iconStore: IconRepository,
private val avatarStore: AvatarRepository,
) {
private val icons = ConcurrentHashMap<Long, ImageBitmap>() private val icons = ConcurrentHashMap<Long, ImageBitmap>()
private val avatars = ConcurrentHashMap<String, Picture>() private val avatars = ConcurrentHashMap<String, Picture>()
@@ -26,7 +30,7 @@ class ServerImages internal constructor(private val conn: TeamspeakConnection) {
fun icon(id: Long): ImageBitmap? { fun icon(id: Long): ImageBitmap? {
if (id == 0L) return null if (id == 0L) return null
icons[id]?.let { return it } icons[id]?.let { return it }
val bitmap = conn.icons.get(id)?.let { decode(it, ICON_PX) } ?: return null val bitmap = iconStore.get(id)?.let { decode(it, ICON_PX) } ?: return null
icons[id] = bitmap icons[id] = bitmap
return bitmap return bitmap
} }
@@ -34,14 +38,14 @@ class ServerImages internal constructor(private val conn: TeamspeakConnection) {
fun avatar(uniqueId: String, flag: String): Picture? { fun avatar(uniqueId: String, flag: String): Picture? {
if (flag.isEmpty()) return null if (flag.isEmpty()) return null
avatars[flag]?.let { return it } avatars[flag]?.let { return it }
val picture = conn.avatars.get(uniqueId, flag)?.let { decodePicture(it.data(), AVATAR_PX) } ?: return null val picture = avatarStore.get(uniqueId, flag)?.let { decodePicture(it.data(), AVATAR_PX) } ?: return null
avatars[flag] = picture avatars[flag] = picture
return picture return picture
} }
/** The avatar's file as the server keeps it; null while it has none or it is still downloading. */ /** The avatar's file as the server keeps it; null while it has none or it is still downloading. */
fun avatarData(uniqueId: String, flag: String): ByteArray? = fun avatarData(uniqueId: String, flag: String): ByteArray? =
if (flag.isEmpty()) null else conn.avatars.get(uniqueId, flag)?.data() if (flag.isEmpty()) null else avatarStore.get(uniqueId, flag)?.data()
/** Decoded no larger than needed: avatars may be far bigger than they are ever shown. */ /** Decoded no larger than needed: avatars may be far bigger than they are ever shown. */
private fun decode(data: ByteArray, maxPx: Int): ImageBitmap? { private fun decode(data: ByteArray, maxPx: Int): ImageBitmap? {
@@ -0,0 +1,34 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import android.net.Uri
import eu.lixko.ts3j.client.config.IdentityStore
import eu.lixko.ts3j.client.config.Settings
import eu.lixko.ts3j.client.contacts.ContactStore
import eu.lixko.ts3j.client.net.ChannelFiles
import eu.lixko.ts3j.client.session.ServerSession
import java.io.File
/** What every server the app is on runs on and reports to, shared by all of them. */
class ServerParts internal constructor(
private val context: Context,
internal val settings: Settings,
private val identityStore: IdentityStore,
private val audio: AudioSetup,
internal val contactStore: ContactStore,
private val myTeamSpeak: MyTeamSpeakAccount,
) {
internal val notifier = MessageNotifier(context)
internal val network = NetworkFollower(context)
internal val cacheDir: File get() = context.cacheDir
internal val attachments get() = myTeamSpeak.attachments
internal fun session(listener: ServerSession.Listener) =
ServerSession(settings, identityStore, audio.audio, audio.sounds, contactStore, listener).also {
it.setMyTeamSpeakLogin(myTeamSpeak.login)
}
internal fun fileTransfers(files: ChannelFiles) = FileTransfers(context, files)
internal suspend fun openShared(uri: Uri) = myTeamSpeak.openShared(uri)
}
@@ -138,6 +138,9 @@ data class ServerTree(
country = c.country.orEmpty(), country = c.country.orEmpty(),
serverGroupIds = c.serverGroupIds.toList(), serverGroupIds = c.serverGroupIds.toList(),
channelGroupId = c.channelGroupId, channelGroupId = c.channelGroupId,
talker = c.talker,
lacksTalkPower = model.lacksTalkPower(c),
talkRequest = c.talkRequest,
) )
} }
} }
@@ -189,4 +192,10 @@ data class ClientItem(
val country: String, val country: String,
val serverGroupIds: List<Int>, val serverGroupIds: List<Int>,
val channelGroupId: Int, val channelGroupId: Int,
/** Granted talk power. */
val talker: Boolean,
/** Short of the channel's needed talk power, so kept from talking. */
val lacksTalkPower: Boolean,
/** Waiting for talk power. */
val talkRequest: Boolean,
) )
@@ -4,48 +4,22 @@ import android.Manifest
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import android.content.pm.PackageManager import android.content.pm.PackageManager
import android.net.Uri
import android.os.Handler import android.os.Handler
import android.os.Looper import android.os.Looper
import android.provider.OpenableColumns
import eu.lixko.ts3j.client.android.audio.AndroidAudioBackend
import eu.lixko.ts3j.client.android.audio.AudioRoute
import eu.lixko.ts3j.client.audio.AudioDevice
import eu.lixko.ts3j.client.config.BanReasonPresets
import eu.lixko.ts3j.client.config.Bookmark import eu.lixko.ts3j.client.config.Bookmark
import eu.lixko.ts3j.client.config.Bookmarks import eu.lixko.ts3j.client.config.Setting
import eu.lixko.ts3j.client.config.IdentityStore
import eu.lixko.ts3j.client.config.Settings import eu.lixko.ts3j.client.config.Settings
import eu.lixko.ts3j.client.config.WhisperList
import eu.lixko.ts3j.client.config.WhisperLists
import eu.lixko.ts3j.client.contacts.Contact
import eu.lixko.ts3j.client.contacts.ContactStore
import eu.lixko.ts3j.client.myts.ChatAttachment
import eu.lixko.ts3j.client.myts.ChatAttachments
import eu.lixko.ts3j.client.myts.MyTeamSpeak
import eu.lixko.ts3j.client.myts.MyTeamSpeakLogin
import eu.lixko.ts3j.client.net.HostButton import eu.lixko.ts3j.client.net.HostButton
import eu.lixko.ts3j.client.net.TeamspeakConnection
import eu.lixko.ts3j.client.session.SelfState import eu.lixko.ts3j.client.session.SelfState
import eu.lixko.ts3j.client.session.ServerLink import eu.lixko.ts3j.client.session.ServerLink
import eu.lixko.ts3j.client.session.ServerSession import eu.lixko.ts3j.client.session.ServerSession
import eu.lixko.ts3j.client.session.Sessions import eu.lixko.ts3j.client.session.Sessions
import eu.lixko.ts3j.client.sound.SoundNotifier
import eu.lixko.ts3j.client.sound.SoundPack
import eu.lixko.ts3j.client.teamspeak.SyncItem
import eu.lixko.ts3j.client.teamspeak.TeamSpeakImporter
import eu.lixko.ts3j.client.teamspeak.TeamSpeakSettingsDb
import eu.lixko.ts3j.client.text.BBCode import eu.lixko.ts3j.client.text.BBCode
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update import kotlinx.coroutines.flow.update
import kotlinx.coroutines.withContext
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicInteger
/** What the app shows of a connection and the local client on it. */ /** What the app shows of a connection and the local client on it. */
@@ -70,11 +44,10 @@ data class SessionState(
val whisper: String? = null, val whisper: String? = null,
/** Whether none of the whisper's channels and clients are on the server, so nobody hears it. */ /** Whether none of the whisper's channels and clients are on the server, so nobody hears it. */
val whisperNobody: Boolean = false, val whisperNobody: Boolean = false,
/** Whether the menus offer whispering, as the bookmark connected with says. */
val whisperControls: Boolean = false,
) )
/** A file to share in chat, open for reading. */
internal class SharedFile(val name: String, val size: Long, val data: InputStream)
/** Something that happened once, for the UI to tell the user about. */ /** Something that happened once, for the UI to tell the user about. */
sealed interface SessionEvent { sealed interface SessionEvent {
data class Poke(val from: String, val message: String) : SessionEvent data class Poke(val from: String, val message: String) : SessionEvent
@@ -88,28 +61,14 @@ sealed interface SessionEvent {
* keeps the process in the foreground while any is connected. Only one server captures with * keeps the process in the foreground while any is connected. Only one server captures with
* the microphone at a time; [Sessions] hands it over. * the microphone at a time; [Sessions] hands it over.
*/ */
class SessionController(private val context: Context) { class SessionController internal constructor(
private val context: Context,
val settings: Settings = Settings.load() private val settings: Settings,
val icons = IconTheme(context, settings) private val identities: IdentityManager,
private val shortcuts = BookmarkShortcuts(context, icons) private val bookmarks: BookmarkManager,
val pictures = WebPictures(context.cacheDir, settings) private val parts: ServerParts,
internal val cacheDir: File get() = context.cacheDir private val levels: LevelMonitor,
internal fun fileTransfers(conn: () -> TeamspeakConnection) = FileTransfers(context, conn) ) {
private val bookmarkStore = Bookmarks.load()
internal val identityStore = IdentityStore.load(settings)
val identities = IdentityManager(context, identityStore, settings, bookmarkStore) {
_bookmarks.value = bookmarkStore.all().toList()
}
internal val audio = AndroidAudioBackend(context)
private val soundPlayer = SpeakingSoundPlayer(context, audio.createSoundPlayer(settings))
internal val sounds = SoundNotifier(settings).also { it.setPlayer(soundPlayer) }
internal val notifier = MessageNotifier(context)
internal val contactStore = ContactStore.load()
/** The reasons offered when adding a ban; shared by every server. */
val banReasons: BanReasonPresets by lazy { BanReasonPresets.load() }
internal val network = NetworkFollower(context)
private val main = Handler(Looper.getMainLooper()) private val main = Handler(Looper.getMainLooper())
private val nextId = AtomicInteger() private val nextId = AtomicInteger()
/** Touched on the main thread only, as [Sessions] wants. */ /** Touched on the main thread only, as [Sessions] wants. */
@@ -131,13 +90,6 @@ class SessionController(private val context: Context) {
private val _lastEnd = MutableStateFlow<String?>(null) private val _lastEnd = MutableStateFlow<String?>(null)
val lastEnd: StateFlow<String?> = _lastEnd val lastEnd: StateFlow<String?> = _lastEnd
/** Copies of the contacts, as the store's own entries change in place. */
private val _contacts = MutableStateFlow(contactCopies())
val contacts: StateFlow<List<Contact>> = _contacts
private val _bookmarks = MutableStateFlow(bookmarkStore.all().toList())
val bookmarks: StateFlow<List<Bookmark>> = _bookmarks
private val _events = MutableSharedFlow<SessionEvent>(extraBufferCapacity = 16) private val _events = MutableSharedFlow<SessionEvent>(extraBufferCapacity = 16)
val events: SharedFlow<SessionEvent> = _events val events: SharedFlow<SessionEvent> = _events
@@ -149,58 +101,42 @@ class SessionController(private val context: Context) {
get() = _onScreen.value get() = _onScreen.value
set(value) { set(value) {
_onScreen.value = value _onScreen.value = value
if (value) notifier.clearPokes() if (value) parts.notifier.clearPokes()
// The process may be let go of any time once out of sight. // The process may be let go of any time once out of sight.
else contactStore.flush() else parts.contactStore.flush()
} }
private val levels = LevelMonitor(settings, audio)
val micLevel: StateFlow<MicLevel> = levels.level val micLevel: StateFlow<MicLevel> = levels.level
@Volatile @Volatile
private var watchingLevel = false private var watchingLevel = false
private val routePrefs = AudioRoutePrefs(context)
private val _route = MutableStateFlow(routePrefs.load())
val route: StateFlow<AudioRoute> = _route
private val _inputDevices = MutableStateFlow(audio.io().inputDevices())
val inputDevices: StateFlow<List<AudioDevice>> = _inputDevices
private val _outputDevices = MutableStateFlow(audio.io().outputDevices())
val outputDevices: StateFlow<List<AudioDevice>> = _outputDevices
val unprocessedSupported: Boolean get() = audio.unprocessedSupported()
init { init {
audio.setRoute(_route.value)
audio.addDeviceListener {
_inputDevices.value = audio.io().inputDevices()
_outputDevices.value = audio.io().outputDevices()
}
// Mutations report on whichever thread made them, a connection thread included. // Mutations report on whichever thread made them, a connection thread included.
contactStore.addListener { parts.contactStore.addListener { _servers.value.forEach(ServerController::contactsChanged) }
_contacts.value = contactCopies() Setting.onAnyChange(::applyOutputSettings, settings.outputDevice, settings.outputVolume, settings.receiveBuffer)
_servers.value.forEach(ServerController::contactsChanged) settings.countryFlags.addListener { servers.value.forEach { it.scheduleTree(structure = false) } }
}
} }
/** The nickname a connect with [identityId] goes by: the identity's own, else the global one. */ val lastAddress: String get() = settings.lastAddress.get()
fun nicknameFor(identityId: String): String = identities.nicknameOf(identityId).ifBlank { settings.nickname }
val lastAddress: String get() = settings.lastAddress
// ---- connection ---- // ---- connection ----
/** Connects to `host[:port]`, as another server; an empty [identityId] means the default identity. */ /** Connects to `host[:port]`, as another server; an empty [identityId] means the default identity. */
fun connect(address: String, nickname: String, password: String = "", identityId: String = "") { fun connect(address: String, nickname: String, password: String = "", identityId: String = "") {
val (host, port) = parseAddress(address) val (host, port) = parseAddress(address)
settings.lastAddress = address settings.lastAddress.set(address)
if (identities.nicknameOf(identityId).isBlank()) settings.nickname = nickname if (identities.nicknameOf(identityId).isBlank()) settings.nickname.set(nickname)
settings.save() settings.save()
start(host, port, nickname, password, identityId, "", "") start(host, port, nickname, password, identityId, "", "")
} }
fun connect(bookmark: Bookmark) { fun connect(bookmark: Bookmark) {
start { it.start(bookmark.address, bookmark.port, bookmark.nickname.orEmpty(), bookmark.password, start {
bookmark.identityId, bookmark.channel, bookmark.channelPassword) } it.session.setMyTeamSpeakFeatures(bookmark.myTeamSpeakFeatures)
it.applyBookmark(bookmark)
it.start(bookmark.address, bookmark.port, bookmark.nickname.orEmpty(), bookmark.password,
bookmark.identityId, bookmark.channel, bookmark.channelPassword)
}
} }
private fun start(host: String, port: Int, nickname: String, password: String, identityId: String, private fun start(host: String, port: Int, nickname: String, password: String, identityId: String,
@@ -209,7 +145,7 @@ class SessionController(private val context: Context) {
} }
private fun start(connect: (ServerController) -> Unit) { private fun start(connect: (ServerController) -> Unit) {
val server = ServerController(nextId.incrementAndGet(), this) val server = ServerController(nextId.incrementAndGet(), parts, this)
sessions.add(server.session) sessions.add(server.session)
_servers.update { it + server } _servers.update { it + server }
_current.value = server _current.value = server
@@ -224,8 +160,7 @@ class SessionController(private val context: Context) {
*/ */
fun open(link: ServerLink, identityId: String = "") { fun open(link: ServerLink, identityId: String = "") {
if (link.bookmarkLabel.isNotEmpty()) { if (link.bookmarkLabel.isNotEmpty()) {
bookmarkStore.add(link.toBookmark()) bookmarks.add(link.toBookmark())
saveBookmarks()
} }
val on = _servers.value.firstOrNull { it.session.isOn(link) } val on = _servers.value.firstOrNull { it.session.isOn(link) }
if (on != null) { if (on != null) {
@@ -239,7 +174,7 @@ class SessionController(private val context: Context) {
/** What a home-screen shortcut does: connects to the bookmark, or goes to its channel when already on its server. */ /** What a home-screen shortcut does: connects to the bookmark, or goes to its channel when already on its server. */
fun openBookmark(id: String): ServerLink? { fun openBookmark(id: String): ServerLink? {
val bookmark = bookmarkStore.find(id) val bookmark = bookmarks.find(id)
if (bookmark == null) { if (bookmark == null) {
error("That bookmark no longer exists") error("That bookmark no longer exists")
return null return null
@@ -253,7 +188,7 @@ class SessionController(private val context: Context) {
fun connectStartupBookmarks(opened: ServerLink?) { fun connectStartupBookmarks(opened: ServerLink?) {
if (startedUp) return if (startedUp) return
startedUp = true startedUp = true
for (b in bookmarkStore.startupBookmarks()) { for (b in bookmarks.startupBookmarks()) {
if (opened?.pointsAt(b.address, b.port) != true) start { it.open(ServerLink.of(b), b.identityId) } if (opened?.pointsAt(b.address, b.port) != true) start { it.open(ServerLink.of(b), b.identityId) }
} }
} }
@@ -267,8 +202,8 @@ class SessionController(private val context: Context) {
val servers = _servers.value val servers = _servers.value
servers.forEach(ServerController::leaving) servers.forEach(ServerController::leaving)
ServerSession.shutdownAll(servers.map { it.session }) ServerSession.shutdownAll(servers.map { it.session })
contactStore.flush() parts.contactStore.flush()
attachments.close() parts.attachments.close()
} }
fun server(id: Int): ServerController? = _servers.value.firstOrNull { it.id == id } fun server(id: Int): ServerController? = _servers.value.firstOrNull { it.id == id }
@@ -310,220 +245,26 @@ class SessionController(private val context: Context) {
internal fun poked(from: String, message: String) { internal fun poked(from: String, message: String) {
_events.tryEmit(SessionEvent.Poke(from, message)) _events.tryEmit(SessionEvent.Poke(from, message))
if (!foreground) notifier.poke(from, BBCode.toPlain(message)) if (!foreground) parts.notifier.poke(from, BBCode.toPlain(message))
} }
internal fun talking(transmitting: Boolean) = levels.talking(transmitting) internal fun talking(transmitting: Boolean) = levels.talking(transmitting)
// ---- bookmarks ---- // ---- what the servers share ----
/** A bookmark to [address] as typed into the connect form, not yet saved. */ /** A saved bookmark changed; the servers connected with it take on what applies at once. */
fun newBookmark(address: String, nickname: String, password: String, identityId: String): Bookmark { internal fun bookmarkEdited(bookmark: Bookmark) = _servers.value.forEach { it.bookmarkEdited(bookmark) }
val (host, port) = parseAddress(address)
// Only a nickname other than the identity's is the server's own.
val own = nickname.takeIf { it != nicknameFor(identityId) }.orEmpty()
return Bookmark(host, host, port, own, password).also { it.identityId = identityId }
}
/** Puts [edited] in place of the bookmark at [index], or adds it when [index] is -1. */ internal fun serverIconChanged(address: String, port: Int, iconId: Long) = bookmarks.serverIconChanged(address, port, iconId)
fun saveBookmark(index: Int, edited: Bookmark) {
val all = bookmarkStore.all()
if (index !in all.indices) {
bookmarkStore.add(edited)
} else {
// The icon may have been learnt meanwhile, and belongs to the server, not to the bookmark.
edited.iconId = all[index].takeIf { it.pointsAt(edited.address, edited.port) }?.iconId ?: 0
all[index] = edited
}
saveBookmarks()
}
/** The channels of a server we are on at [host]:[port], to pick one to join. */ /** The channels of a server we are on at [host]:[port], to pick one to join. */
fun channelPathsAt(host: String, port: Int): List<String> = fun channelPathsAt(host: String, port: Int): List<String> = sessions.connectedTo(host, port)?.channelPaths().orEmpty()
_servers.value.firstOrNull {
it.isConnected && it.session.port() == port && it.session.address().equals(host.trim(), ignoreCase = true)
}?.session?.channelPaths().orEmpty()
fun removeBookmark(bookmark: Bookmark) { /** The channel we are in on the server at [host]:[port]; null when we are not on it. */
val index = bookmarkStore.all().indexOf(bookmark) fun currentChannelAt(host: String, port: Int): String? = sessions.connectedTo(host, port)?.currentChannelPath()
if (index < 0) return
bookmarkStore.remove(index)
saveBookmarks()
}
/** Bookmarks leading to [address]:[port] take on the icon the server shows now. */ /** Signed in or out of myTeamSpeak. */
internal fun serverIconChanged(address: String, port: Int, iconId: Long) { internal fun myTeamSpeakChanged() = _servers.value.forEach { it.session.updateMyTeamSpeak() }
main.post {
val all = bookmarkStore.all()
var changed = false
for (i in all.indices) {
val b = all[i]
if (!b.pointsAt(address, port) || b.iconId == iconId) continue
// A new entry, so the list the UI holds changes along with it.
all[i] = b.copy().also { it.iconId = iconId }
changed = true
}
if (changed) saveBookmarks()
}
}
private fun saveBookmarks() {
bookmarkStore.save()
_bookmarks.value = bookmarkStore.all().toList()
shortcuts.sync(_bookmarks.value)
}
val canPinShortcuts: Boolean get() = shortcuts.supported
/** Asks the launcher for a home-screen shortcut connecting to [bookmark]. */
fun pinShortcut(bookmark: Bookmark) {
// A bookmark not saved since ids came in has a new one on every load until it is.
bookmarkStore.save()
shortcuts.pin(bookmark)
}
// ---- whisper lists ----
private val whisperListStore = WhisperLists.load()
private val _whisperLists = MutableStateFlow(whisperListCopies())
val whisperLists: StateFlow<List<WhisperList>> = _whisperLists
private fun whisperListCopies() = whisperListStore.all().map { it.copy() }
/** Puts [list] in place of the one at [index], or adds it when [index] is -1. */
fun saveWhisperList(index: Int, list: WhisperList) {
val all = whisperListStore.all()
if (index in all.indices) all[index] = list.copy() else all.add(list.copy())
whisperListStore.save()
_whisperLists.value = whisperListCopies()
}
/** Adds a channel or a client to the list at [index], or to a new list named [newName] when [index] is -1. */
fun addToWhisperList(index: Int, newName: String, add: (WhisperList) -> Unit) {
val list = whisperListStore.all().getOrNull(index)?.copy() ?: WhisperList(newName)
add(list)
saveWhisperList(index, list)
}
fun removeWhisperList(index: Int) {
val all = whisperListStore.all()
if (index !in all.indices) return
all.removeAt(index)
whisperListStore.save()
_whisperLists.value = whisperListCopies()
}
// ---- contacts ----
private fun contactCopies(): List<Contact> = contactStore.all().map { it.copy() }
/** A copy of the contact to edit and hand back to [saveContact]. */
fun contact(uniqueId: String): Contact? = contactStore.find(uniqueId)?.copy()
fun saveContact(contact: Contact) = contactStore.put(contact)
fun removeContact(uniqueId: String) = contactStore.remove(uniqueId)
/**
* Adds the contacts of a TeamSpeak 3 `settings.db`, overwriting entries for the same clients.
*
* @return how many contacts the file held and how many of them were new
*/
suspend fun importContacts(uri: Uri): Pair<Int, Int> = withContext(Dispatchers.IO) {
val found = withLocalCopy(context, uri, TeamSpeakSettingsDb::readContacts)
found.size to if (found.isEmpty()) 0 else contactStore.merge(found)
}
// ---- myTeamSpeak ----
/** The account the app stays signed in to; its reads block, so they run on [Dispatchers.IO]. */
val myTeamSpeak: MyTeamSpeakLogin = MyTeamSpeakLogin.load()
private val importer = TeamSpeakImporter(identityStore, bookmarkStore, settings)
private val _myTeamSpeakSignedIn = MutableStateFlow(myTeamSpeak.isSignedIn)
val myTeamSpeakSignedIn: StateFlow<Boolean> = _myTeamSpeakSignedIn
/** Files shared in chat, kept in the myTeamSpeak account's cloud storage. */
internal val attachments = ChatAttachments(myTeamSpeak).also {
pictures.addSource(ChatAttachment.SCHEME, it::fetchPicture)
}
suspend fun signInMyTeamSpeak(email: String, password: String): MyTeamSpeak.Account =
withContext(Dispatchers.IO) { myTeamSpeak.signIn(email, password) }
.also {
_myTeamSpeakSignedIn.value = true
// Shared pictures that could not be had signed out.
pictures.retryFailed()
}
suspend fun fetchMyTeamSpeak(): MyTeamSpeak.Account =
try {
withContext(Dispatchers.IO) { myTeamSpeak.fetch() }
} finally {
// A sign-in the server no longer takes has signed out.
_myTeamSpeakSignedIn.value = myTeamSpeak.isSignedIn
}
suspend fun signOutMyTeamSpeak() {
myTeamSpeak.signOut()
_myTeamSpeakSignedIn.value = false
withContext(Dispatchers.IO) { attachments.close() }
}
/** Fetches a file shared in chat whole. */
suspend fun downloadAttachment(ref: ChatAttachment.Ref): ByteArray =
withContext(Dispatchers.IO) { attachments.download(ref, ChatAttachments.MAX_UPLOAD_BYTES) }
/** Fetches a file shared in chat into [uri], e.g. one the user picked to save it as. */
suspend fun saveAttachment(ref: ChatAttachment.Ref, uri: Uri) {
val data = downloadAttachment(ref)
withContext(Dispatchers.IO) {
val out = context.contentResolver.openOutputStream(uri) ?: throw IOException("Could not write the file")
out.use { it.write(data) }
}
}
/** A file picked to share in chat, or why it cannot be. */
internal suspend fun openShared(uri: Uri): Result<SharedFile> = withContext(Dispatchers.IO) {
runCatching {
val resolver = context.contentResolver
val (name, size) = resolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE),
null, null, null)?.use { c ->
if (!c.moveToFirst()) null
else c.getString(0).orEmpty() to (if (c.isNull(1)) -1L else c.getLong(1))
} ?: ("" to -1L)
when {
size < 0 -> throw IOException("Could not read the file's size")
size > ChatAttachments.MAX_UPLOAD_BYTES ->
throw IOException("Files over ${ChatAttachments.MAX_UPLOAD_BYTES shr 20} MB cannot be shared")
}
val data = resolver.openInputStream(uri) ?: throw IOException("Could not read the file")
SharedFile(name.ifBlank { uri.lastPathSegment ?: "file" }, size, data)
}
}
fun isImported(item: SyncItem): Boolean = importer.isPresent(item)
/** Imports [chosen] out of the account's [all] items, with the identities the chosen bookmarks use. */
suspend fun importMyTeamSpeak(all: List<SyncItem>, chosen: List<SyncItem>): TeamSpeakImporter.Result =
withContext(Dispatchers.IO) { importer.importSelected(all, chosen) }
.also {
_bookmarks.value = bookmarkStore.all().toList()
identities.refresh()
}
// ---- sound packs ----
private val _soundPacks = MutableStateFlow(sounds.availablePacks())
val soundPacks: StateFlow<List<SoundPack>> = _soundPacks
val soundPack: SoundPack? get() = sounds.pack()
fun setCountryFlags(shown: Boolean) {
settings.countryFlags = shown
settings.save()
servers.value.forEach { it.scheduleTree(structure = false) }
}
/** Puts new client row colours, already set in [settings], into effect. */ /** Puts new client row colours, already set in [settings], into effect. */
fun clientRowColorsChanged() { fun clientRowColorsChanged() {
@@ -531,23 +272,6 @@ class SessionController(private val context: Context) {
servers.value.forEach { it.scheduleTree(structure = false) } servers.value.forEach { it.scheduleTree(structure = false) }
} }
fun setDescriptionPictures(shown: Boolean) {
settings.descriptionPictures = shown
settings.save()
}
fun setSoundPack(pack: SoundPack) {
sounds.setPack(pack)
settings.save()
}
/** Unpacks the packs the app ships with, when this version has not yet. */
fun installSoundPacks() {
if (!SoundPackInstaller(context).install()) return
sounds.reload()
_soundPacks.value = sounds.availablePacks()
}
// ---- the local client ---- // ---- the local client ----
fun hasMicPermission() = fun hasMicPermission() =
@@ -574,33 +298,19 @@ class SessionController(private val context: Context) {
updateLevels() updateLevels()
} }
private val overlayPrefs = context.getSharedPreferences("overlay", Context.MODE_PRIVATE)
private val _pttOverlay = MutableStateFlow(overlayPrefs.getBoolean(OVERLAY_ENABLED, false))
/** Whether push to talk floats a button over other apps while this one is off screen. */
val pttOverlay: StateFlow<Boolean> = _pttOverlay
fun setPttOverlay(enabled: Boolean) {
overlayPrefs.edit().putBoolean(OVERLAY_ENABLED, enabled).apply()
_pttOverlay.value = enabled
}
/** Switches between push to talk and voice activation; returns the new mode. */ /** Switches between push to talk and voice activation; returns the new mode. */
fun toggleInputMode(): Settings.InputMode { fun toggleInputMode(): Settings.InputMode {
settings.inputMode = if (settings.inputMode == Settings.InputMode.PUSH_TO_TALK) settings.inputMode.set(if (settings.inputMode.get() == Settings.InputMode.PUSH_TO_TALK)
Settings.InputMode.VOICE_ACTIVATION else Settings.InputMode.PUSH_TO_TALK Settings.InputMode.VOICE_ACTIVATION else Settings.InputMode.PUSH_TO_TALK)
applySettings() applySettings()
return settings.inputMode return settings.inputMode.get()
} }
/** Saves the settings and puts the voice and device ones into effect at once. */ /** Saves the settings and puts the voice ones into effect at once. */
fun applySettings() { fun applySettings() {
settings.save() settings.save()
soundPlayer.setOutputDevice(settings.outputDevice)
try { try {
for (server in _servers.value) { for (server in _servers.value) {
server.playback?.setMasterVolume(settings.outputVolume)
server.playback?.setOutputDevice(settings.outputDevice)
server.playback?.setReceiveBuffer(settings.receiveBuffer)
server.microphone?.apply(settings) server.microphone?.apply(settings)
server.refresh() server.refresh()
server.scheduleTree(structure = false) server.scheduleTree(structure = false)
@@ -611,11 +321,13 @@ class SessionController(private val context: Context) {
} }
} }
/** Microphone preset and playback usage; the open lines move over at once. */ /** Output device, volume and receive buffer are global, so they go to every connection. */
fun setRoute(route: AudioRoute) { private fun applyOutputSettings() {
routePrefs.save(route) for (server in _servers.value) {
_route.value = route server.playback?.setMasterVolume(settings.outputVolume.get())
audio.setRoute(route) server.playback?.setOutputDevice(settings.outputDevice.get())
server.playback?.setReceiveBuffer(settings.receiveBuffer.get())
}
} }
/** Listens to the microphone for the level meter while [on]. */ /** Listens to the microphone for the level meter while [on]. */
@@ -640,12 +352,11 @@ class SessionController(private val context: Context) {
/** Answers a private message from its notification. */ /** Answers a private message from its notification. */
fun reply(serverId: Int, clientId: Int, text: String) { fun reply(serverId: Int, clientId: Int, text: String) {
server(serverId)?.reply(clientId, text) ?: notifier.clear(serverId, clientId) server(serverId)?.reply(clientId, text) ?: parts.notifier.clear(serverId, clientId)
} }
companion object { companion object {
const val DEFAULT_PORT = 9987 const val DEFAULT_PORT = 9987
private const val OVERLAY_ENABLED = "enabled"
/** `host[:port]` as typed, the port defaulting to TeamSpeak's. */ /** `host[:port]` as typed, the port defaulting to TeamSpeak's. */
fun parseAddress(address: String): Pair<String, Int> { fun parseAddress(address: String): Pair<String, Int> {
@@ -0,0 +1,37 @@
package eu.lixko.ts3j.client.android
import android.content.Context
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
/** What a sideways swipe over the channel tree does. */
enum class TreeSwipe { OFF, CHAT, SERVERS }
/** The swipe gestures, an Android-only choice kept apart from the shared settings. */
class SwipePrefs(context: Context) {
private val prefs = context.getSharedPreferences("swipe", Context.MODE_PRIVATE)
private val _tree = MutableStateFlow(
TreeSwipe.entries.firstOrNull { it.name == prefs.getString(TREE, null) } ?: TreeSwipe.CHAT)
val tree: StateFlow<TreeSwipe> = _tree
private val _chatTabs = MutableStateFlow(prefs.getBoolean(CHAT_TABS, true))
/** Whether a sideways swipe over the chat goes to the neighbouring conversation. */
val chatTabs: StateFlow<Boolean> = _chatTabs
fun setTree(swipe: TreeSwipe) {
prefs.edit().putString(TREE, swipe.name).apply()
_tree.value = swipe
}
fun setChatTabs(enabled: Boolean) {
prefs.edit().putBoolean(CHAT_TABS, enabled).apply()
_chatTabs.value = enabled
}
private companion object {
const val TREE = "tree"
const val CHAT_TABS = "chatTabs"
}
}
@@ -5,14 +5,16 @@ import eu.lixko.ts3j.client.config.AppDirs
class Ts3Application : Application() { class Ts3Application : Application() {
lateinit var sessions: SessionController lateinit var parts: AppParts
private set private set
val sessions: SessionController get() = parts.sessions
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
// Before any store loads: there is no home directory to find them in. // Before any store loads: there is no home directory to find them in.
AppDirs.init(filesDir, filesDir.toPath().resolve("chats")) AppDirs.init(filesDir, filesDir.toPath().resolve("chats"))
sessions = SessionController(this) parts = AppParts(this)
Thread(sessions::installSoundPacks, "sound-packs").start() Thread(parts.audio::installSoundPacks, "sound-packs").start()
} }
} }
@@ -39,7 +39,7 @@ class WebPictures(cacheDir: File, private val settings: Settings) {
fun retryFailed() = downloads.retryFailed() fun retryFailed() = downloads.retryFailed()
/** Whether pictures are shown at all, rather than links to them. */ /** Whether pictures are shown at all, rather than links to them. */
val enabled: Boolean get() = settings.descriptionPictures val enabled: Boolean get() = settings.descriptionPictures.get()
suspend fun state(url: String): State { suspend fun state(url: String): State {
decoded.get(url)?.let { return State.Shown(it) } decoded.get(url)?.let { return State.Shown(it) }
@@ -0,0 +1,41 @@
package eu.lixko.ts3j.client.android
import eu.lixko.ts3j.client.config.WhisperList
import eu.lixko.ts3j.client.config.WhisperLists
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
/** The saved whisper lists, shared by every server. */
class WhisperListManager internal constructor() {
private val store = WhisperLists.load()
private val _all = MutableStateFlow(copies())
val all: StateFlow<List<WhisperList>> = _all
private fun copies() = store.all().map { it.copy() }
/** Puts [list] in place of the one at [index], or adds it when [index] is -1. */
fun save(index: Int, list: WhisperList) {
val all = store.all()
if (index in all.indices) all[index] = list.copy() else all.add(list.copy())
saved()
}
/** Adds a channel or a client to the list at [index], or to a new list named [newName] when [index] is -1. */
fun addTo(index: Int, newName: String, add: (WhisperList) -> Unit) {
val list = store.all().getOrNull(index)?.copy() ?: WhisperList(newName)
add(list)
save(index, list)
}
fun remove(index: Int) {
val all = store.all()
if (index !in all.indices) return
all.removeAt(index)
saved()
}
private fun saved() {
store.save()
_all.value = copies()
}
}
@@ -4,6 +4,7 @@ import android.Manifest
import android.content.pm.PackageManager import android.content.pm.PackageManager
import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.AlertDialog import androidx.compose.material3.AlertDialog
import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text import androidx.compose.material3.Text
@@ -17,14 +18,17 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.saveable.rememberSaveableStateHolder import androidx.compose.runtime.saveable.rememberSaveableStateHolder
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.SessionController import eu.lixko.ts3j.client.android.AppParts
import eu.lixko.ts3j.client.android.SessionEvent import eu.lixko.ts3j.client.android.SessionEvent
import eu.lixko.ts3j.client.android.TreeSwipe
@Composable @Composable
fun App(vm: SessionController) { fun App(parts: AppParts) {
val current by vm.current.collectAsStateWithLifecycle() val sessions = parts.sessions
val current by sessions.current.collectAsStateWithLifecycle()
// Each server keeps its own screen state (chat open, conversation) while another is shown. // Each server keeps its own screen state (chat open, conversation) while another is shown.
val serverStates = rememberSaveableStateHolder() val serverStates = rememberSaveableStateHolder()
var connectOpen by rememberSaveable { mutableStateOf(false) } var connectOpen by rememberSaveable { mutableStateOf(false) }
@@ -38,8 +42,8 @@ fun App(vm: SessionController) {
var editingBookmark by rememberSaveable(stateSaver = BookmarkEditSaver) { mutableStateOf<BookmarkEdit?>(null) } var editingBookmark by rememberSaveable(stateSaver = BookmarkEditSaver) { mutableStateOf<BookmarkEdit?>(null) }
var poke by remember { mutableStateOf<SessionEvent.Poke?>(null) } var poke by remember { mutableStateOf<SessionEvent.Poke?>(null) }
LaunchedEffect(vm) { LaunchedEffect(sessions) {
vm.events.collect { event -> sessions.events.collect { event ->
when (event) { when (event) {
is SessionEvent.Poke -> poke = event is SessionEvent.Poke -> poke = event
is SessionEvent.Error -> snackbar.showSnackbar(event.message) is SessionEvent.Error -> snackbar.showSnackbar(event.message)
@@ -56,7 +60,7 @@ fun App(vm: SessionController) {
val context = LocalContext.current val context = LocalContext.current
val permissions = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { granted -> val permissions = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { granted ->
if (granted[Manifest.permission.RECORD_AUDIO] == true) vm.current.value?.let(vm::giveMicrophoneTo) if (granted[Manifest.permission.RECORD_AUDIO] == true) sessions.current.value?.let(sessions::giveMicrophoneTo)
} }
fun missing(vararg names: String) = fun missing(vararg names: String) =
names.filter { context.checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED } names.filter { context.checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
@@ -69,7 +73,7 @@ fun App(vm: SessionController) {
if (ask.isNotEmpty()) permissions.launch(ask.toTypedArray()) if (ask.isNotEmpty()) permissions.launch(ask.toTypedArray())
} }
val enableMicrophone: () -> Unit = { val enableMicrophone: () -> Unit = {
if (missing(Manifest.permission.RECORD_AUDIO).isEmpty()) vm.current.value?.let(vm::giveMicrophoneTo) if (missing(Manifest.permission.RECORD_AUDIO).isEmpty()) sessions.current.value?.let(sessions::giveMicrophoneTo)
else permissions.launch(arrayOf(Manifest.permission.RECORD_AUDIO)) else permissions.launch(arrayOf(Manifest.permission.RECORD_AUDIO))
} }
@@ -79,29 +83,43 @@ fun App(vm: SessionController) {
contactDirect = uniqueId != null contactDirect = uniqueId != null
} }
CompositionLocalProvider(LocalIconTheme provides vm.icons, LocalWebPictures provides vm.pictures) { CompositionLocalProvider(LocalIconTheme provides parts.icons, LocalWebPictures provides parts.pictures) {
val server = current val server = current
val bookmark = editingBookmark val bookmark = editingBookmark
when { when {
bookmark != null -> BookmarkScreen(vm, bookmark, onDone = { editingBookmark = null }) bookmark != null -> BookmarkScreen(sessions, parts.bookmarks, parts.identities, bookmark, onDone = { editingBookmark = null })
contactsOpen -> ContactsScreen(vm, editingContact, onEdit = { uniqueId -> contactsOpen -> ContactsScreen(parts.contacts, editingContact, onEdit = { uniqueId ->
if (uniqueId == null && contactDirect) contactsOpen = false if (uniqueId == null && contactDirect) contactsOpen = false
contactDirect = false contactDirect = false
editingContact = uniqueId editingContact = uniqueId
}, onBack = { contactsOpen = false }) }, onBack = { contactsOpen = false })
myTeamSpeakOpen -> MyTeamSpeakScreen(vm, onBack = { myTeamSpeakOpen = false }) myTeamSpeakOpen -> MyTeamSpeakScreen(parts.myTeamSpeak, onBack = { myTeamSpeakOpen = false })
settingsOpen -> SettingsScreen(vm, onContacts = { openContacts(null) }, onBack = { settingsOpen = false }) settingsOpen -> SettingsScreen(parts, onContacts = { openContacts(null) }, onBack = { settingsOpen = false })
server != null && !connectOpen -> { server != null && !connectOpen -> {
serverStates.SaveableStateProvider(server.id) { val servers by sessions.servers.collectAsStateWithLifecycle()
CompositionLocalProvider(LocalServerImages provides server.images) { val treeSwipe by parts.swipe.tree.collectAsStateWithLifecycle()
PictureViewerHost(server) { val serverSwipe = rememberSwipeState()
ServerScreen(vm, server, snackbar, { settingsOpen = true }, openContacts, enableMicrophone, SwipeHost(
onConnectOther = { connectOpen = true }, onEditBookmark = { editingBookmark = it }) serverSwipe, server,
neighbour = { at, dir ->
if (treeSwipe != TreeSwipe.SERVERS) null
else servers.indexOf(at).takeIf { it >= 0 }?.let { servers.getOrNull(it + dir) }
},
onSwipe = sessions::select,
modifier = Modifier.fillMaxSize(),
) { shown ->
serverStates.SaveableStateProvider(shown.id) {
CompositionLocalProvider(LocalServerImages provides shown.images) {
PictureViewerHost(shown) {
ServerScreen(sessions, parts.whisperLists, parts.myTeamSpeak, parts.swipe, parts.banReasons, shown, snackbar, { settingsOpen = true }, openContacts, enableMicrophone,
onConnectOther = { connectOpen = true }, onEditBookmark = { editingBookmark = it },
serverSwipe = serverSwipe, active = shown == server)
} }
} }
} }
} }
else -> ConnectScreen(vm, snackbar, { settingsOpen = true }, { myTeamSpeakOpen = true }, connectAsking, }
else -> ConnectScreen(sessions, parts.bookmarks, parts.identities, parts.myTeamSpeak, snackbar, { settingsOpen = true }, { myTeamSpeakOpen = true }, connectAsking,
onEditBookmark = { editingBookmark = it }, onEditBookmark = { editingBookmark = it },
onBack = if (current != null) ({ connectOpen = false }) else null) onBack = if (current != null) ({ connectOpen = false }) else null)
} }
@@ -17,13 +17,13 @@ import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.ChatKey import eu.lixko.ts3j.client.android.MyTeamSpeakAccount
import eu.lixko.ts3j.client.android.ServerController import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.android.SessionController import eu.lixko.ts3j.client.chat.ChatKey
import eu.lixko.ts3j.client.myts.ChatAttachment import eu.lixko.ts3j.client.myts.ChatAttachment
import eu.lixko.ts3j.client.myts.MyTsException import eu.lixko.ts3j.client.myts.MyTsException
import kotlinx.coroutines.launch
import java.io.IOException import java.io.IOException
import kotlinx.coroutines.launch
/** What the chat does with shared files: [open] one it links to, [share] one into a conversation. */ /** What the chat does with shared files: [open] one it links to, [share] one into a conversation. */
class AttachmentActions(val open: (String) -> Unit, val share: () -> Unit) class AttachmentActions(val open: (String) -> Unit, val share: () -> Unit)
@@ -34,15 +34,16 @@ class AttachmentActions(val open: (String) -> Unit, val share: () -> Unit)
*/ */
@Composable @Composable
fun rememberAttachmentActions( fun rememberAttachmentActions(
vm: SessionController, account: MyTeamSpeakAccount,
server: ServerController, server: ServerController,
snackbar: SnackbarHostState, snackbar: SnackbarHostState,
shown: ChatKey, shown: ChatKey,
): AttachmentActions { ): AttachmentActions {
val scope = rememberCoroutineScope() val scope = rememberCoroutineScope()
val signedIn by vm.myTeamSpeakSignedIn.collectAsStateWithLifecycle() val signedIn by account.signedIn.collectAsStateWithLifecycle()
val key by rememberUpdatedState(shown) val key by rememberUpdatedState(shown)
val viewer = LocalPictureViewer.current val viewer = LocalPictureViewer.current
val pictures = LocalWebPictures.current
val tell = { message: String -> scope.launch { snackbar.showSnackbar(message) }; Unit } val tell = { message: String -> scope.launch { snackbar.showSnackbar(message) }; Unit }
var saving by rememberSaveable { mutableStateOf<String?>(null) } var saving by rememberSaveable { mutableStateOf<String?>(null) }
@@ -52,7 +53,7 @@ fun rememberAttachmentActions(
if (uri == null || ref == null) return@rememberLauncherForActivityResult if (uri == null || ref == null) return@rememberLauncherForActivityResult
scope.launch { scope.launch {
val error = try { val error = try {
vm.saveAttachment(ref, uri) account.saveAttachment(ref, uri)
null null
} catch (e: MyTsException) { } catch (e: MyTsException) {
e.message e.message
@@ -72,7 +73,7 @@ fun rememberAttachmentActions(
when { when {
!signedIn -> tell(SIGN_IN) !signedIn -> tell(SIGN_IN)
ref.isImage() && viewer != null -> viewer(ViewedPicture(ref.fileName.substringBeforeLast('.')) { ref.isImage() && viewer != null -> viewer(ViewedPicture(ref.fileName.substringBeforeLast('.')) {
vm.pictures.data(href) ?: runCatching { vm.downloadAttachment(ref) }.getOrNull() pictures?.data(href) ?: runCatching { account.downloadAttachment(ref) }.getOrNull()
}) })
else -> { else -> {
saving = href saving = href
@@ -92,10 +92,9 @@ fun BanListScreen(server: ServerController, presets: BanReasonPresets, onBack: (
} }
/** Reports a failed change, or re-reads the list to show what the server now holds. */ /** Reports a failed change, or re-reads the list to show what the server now holds. */
val change = { action: suspend () -> String?, failure: String -> val change = { action: suspend () -> Result<Unit>, failure: String ->
scope.launch { scope.launch {
val error = action() action().onFailure { snackbar.showSnackbar("$failure: ${it.message}") }
if (error != null) snackbar.showSnackbar("$failure: $error")
generation++ generation++
} }
Unit Unit
@@ -103,7 +102,7 @@ fun BanListScreen(server: ServerController, presets: BanReasonPresets, onBack: (
edit?.let { e -> edit?.let { e ->
val existing = (e as? BanEdit.Existing)?.ban val existing = (e as? BanEdit.Existing)?.ban
BanEditor(existing, presets, server.maxBanSeconds, onBack = { edit = null }) { rule -> BanEditor(existing, presets, server.permissions.maxBanSeconds(), onBack = { edit = null }) { rule ->
edit = null edit = null
if (existing == null) change({ server.addBan(rule) }, "Error adding ban") if (existing == null) change({ server.addBan(rule) }, "Error adding ban")
else change({ server.replaceBan(existing.id, rule) }, "Error editing ban") else change({ server.replaceBan(existing.id, rule) }, "Error editing ban")
@@ -114,7 +113,7 @@ fun BanListScreen(server: ServerController, presets: BanReasonPresets, onBack: (
SubScreen( SubScreen(
"Ban list", onBack, "Ban list", onBack,
actions = { actions = {
if (server.canCreateBans) IconButton(onClick = { edit = BanEdit.New }) { PackIcon("ADD", "Add") } if (server.permissions.canCreateBans()) IconButton(onClick = { edit = BanEdit.New }) { PackIcon("ADD", "Add") }
IconButton(onClick = { generation++ }) { PackIcon("REFRESH", "Reload") } IconButton(onClick = { generation++ }) { PackIcon("REFRESH", "Reload") }
}, },
snackbar = snackbar, snackbar = snackbar,
@@ -1,7 +1,7 @@
package eu.lixko.ts3j.client.android.ui package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.clickable import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
@@ -15,6 +15,7 @@ import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuAnchorType import androidx.compose.material3.ExposedDropdownMenuAnchorType
import androidx.compose.material3.ExposedDropdownMenuBox import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.IconButton
import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Switch import androidx.compose.material3.Switch
import androidx.compose.material3.Text import androidx.compose.material3.Text
@@ -32,6 +33,8 @@ import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.BookmarkManager
import eu.lixko.ts3j.client.android.IdentityManager
import eu.lixko.ts3j.client.android.SessionController import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.config.Bookmark import eu.lixko.ts3j.client.config.Bookmark
@@ -42,7 +45,8 @@ val BookmarkEditSaver = listSaver<BookmarkEdit?, Any>(
save = { edit -> save = { edit ->
val b = edit?.bookmark ?: return@listSaver emptyList() val b = edit?.bookmark ?: return@listSaver emptyList()
listOf(edit.index, b.label.orEmpty(), b.address.orEmpty(), b.port, b.nickname.orEmpty(), b.password, listOf(edit.index, b.label.orEmpty(), b.address.orEmpty(), b.port, b.nickname.orEmpty(), b.password,
b.identityId, b.channel, b.channelPassword, b.connectOnStartup, b.iconId, b.id) b.identityId, b.channel, b.channelPassword, b.connectOnStartup, b.iconId, b.id,
b.myTeamSpeakFeatures, b.showWhisperControls)
}, },
restore = { saved -> restore = { saved ->
if (saved.isEmpty()) null if (saved.isEmpty()) null
@@ -54,15 +58,17 @@ val BookmarkEditSaver = listSaver<BookmarkEdit?, Any>(
connectOnStartup = saved[9] as Boolean connectOnStartup = saved[9] as Boolean
iconId = saved[10] as Long iconId = saved[10] as Long
id = saved[11] as String id = saved[11] as String
myTeamSpeakFeatures = saved[12] as Boolean
showWhisperControls = saved[13] as Boolean
}) })
}, },
) )
/** Every setting of one bookmark, saved only on Save. */ /** Every setting of one bookmark, saved only on Save. */
@Composable @Composable
fun BookmarkScreen(vm: SessionController, edit: BookmarkEdit, onDone: () -> Unit) { fun BookmarkScreen(sessions: SessionController, bookmarks: BookmarkManager, identityManager: IdentityManager, edit: BookmarkEdit, onDone: () -> Unit) {
val b = edit.bookmark val b = edit.bookmark
val identities by vm.identities.all.collectAsStateWithLifecycle() val identities by identityManager.all.collectAsStateWithLifecycle()
var label by rememberSaveable { mutableStateOf(b.label.orEmpty()) } var label by rememberSaveable { mutableStateOf(b.label.orEmpty()) }
var address by rememberSaveable { var address by rememberSaveable {
mutableStateOf(if (b.port == SessionController.DEFAULT_PORT) b.address.orEmpty() else "${b.address}:${b.port}") mutableStateOf(if (b.port == SessionController.DEFAULT_PORT) b.address.orEmpty() else "${b.address}:${b.port}")
@@ -73,10 +79,12 @@ fun BookmarkScreen(vm: SessionController, edit: BookmarkEdit, onDone: () -> Unit
var channel by rememberSaveable { mutableStateOf(b.channel.orEmpty()) } var channel by rememberSaveable { mutableStateOf(b.channel.orEmpty()) }
var channelPassword by rememberSaveable { mutableStateOf(b.channelPassword.orEmpty()) } var channelPassword by rememberSaveable { mutableStateOf(b.channelPassword.orEmpty()) }
var connectOnStartup by rememberSaveable { mutableStateOf(b.connectOnStartup) } var connectOnStartup by rememberSaveable { mutableStateOf(b.connectOnStartup) }
var myTeamSpeakFeatures by rememberSaveable { mutableStateOf(b.myTeamSpeakFeatures) }
var showWhisperControls by rememberSaveable { mutableStateOf(b.showWhisperControls) }
val save = { val save = {
val (host, port) = SessionController.parseAddress(address) val (host, port) = SessionController.parseAddress(address)
vm.saveBookmark(edit.index, b.copy().also { bookmarks.save(edit.index, b.copy().also {
it.label = label.trim().ifEmpty { host } it.label = label.trim().ifEmpty { host }
it.address = host it.address = host
it.port = port it.port = port
@@ -86,6 +94,8 @@ fun BookmarkScreen(vm: SessionController, edit: BookmarkEdit, onDone: () -> Unit
it.channel = channel.trim() it.channel = channel.trim()
it.channelPassword = channelPassword it.channelPassword = channelPassword
it.connectOnStartup = connectOnStartup it.connectOnStartup = connectOnStartup
it.myTeamSpeakFeatures = myTeamSpeakFeatures
it.showWhisperControls = showWhisperControls
}) })
onDone() onDone()
} }
@@ -106,11 +116,14 @@ fun BookmarkScreen(vm: SessionController, edit: BookmarkEdit, onDone: () -> Unit
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password)) keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password))
IdentityField(identities, identityId) { identityId = it } IdentityField(identities, identityId) { identityId = it }
OutlinedTextField(nickname, { nickname = it }, Modifier.fillMaxWidth(), label = { Text("Nickname") }, OutlinedTextField(nickname, { nickname = it }, Modifier.fillMaxWidth(), label = { Text("Nickname") },
placeholder = { Text(vm.nicknameFor(identityId)) }, singleLine = true) placeholder = { Text(identityManager.nicknameFor(identityId)) }, singleLine = true)
val paths = remember(address) { val paths = remember(address) {
SessionController.parseAddress(address).let { (host, port) -> vm.channelPathsAt(host, port) } SessionController.parseAddress(address).let { (host, port) -> sessions.channelPathsAt(host, port) }
} }
ChannelField(channel, paths) { channel = it } val current = remember(address) {
SessionController.parseAddress(address).let { (host, port) -> sessions.currentChannelAt(host, port) }
}
ChannelField(channel, paths, current) { channel = it }
OutlinedTextField(channelPassword, { channelPassword = it }, Modifier.fillMaxWidth(), OutlinedTextField(channelPassword, { channelPassword = it }, Modifier.fillMaxWidth(),
label = { Text("Channel password") }, singleLine = true, label = { Text("Channel password") }, singleLine = true,
visualTransformation = PasswordVisualTransformation(), visualTransformation = PasswordVisualTransformation(),
@@ -120,14 +133,27 @@ fun BookmarkScreen(vm: SessionController, edit: BookmarkEdit, onDone: () -> Unit
Text("Connect on startup", Modifier.weight(1f)) Text("Connect on startup", Modifier.weight(1f))
Switch(connectOnStartup, { connectOnStartup = it }) Switch(connectOnStartup, { connectOnStartup = it })
} }
Row(Modifier.fillMaxWidth().clickable { myTeamSpeakFeatures = !myTeamSpeakFeatures },
verticalAlignment = Alignment.CenterVertically) {
Text("Enable myTeamSpeak features", Modifier.weight(1f))
Switch(myTeamSpeakFeatures, { myTeamSpeakFeatures = it })
}
Row(Modifier.fillMaxWidth().clickable { showWhisperControls = !showWhisperControls },
verticalAlignment = Alignment.CenterVertically) {
Text("Show whisper controls", Modifier.weight(1f))
Switch(showWhisperControls, { showWhisperControls = it })
}
} }
} }
} }
/** The channel to join, typed or picked among [paths] of the server when we are on it. */ /**
* The channel to join, typed or picked among [paths] of the server when we are on it,
* or taken from [current], the one we are in there.
*/
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
private fun ChannelField(channel: String, paths: List<String>, onChange: (String) -> Unit) { private fun ChannelField(channel: String, paths: List<String>, current: String?, onChange: (String) -> Unit) {
var open by remember { mutableStateOf(false) } var open by remember { mutableStateOf(false) }
// A channel already picked lists them all, for picking another. // A channel already picked lists them all, for picking another.
val matches = if (channel in paths) paths else paths.filter { it.contains(channel.trim(), ignoreCase = true) } val matches = if (channel in paths) paths else paths.filter { it.contains(channel.trim(), ignoreCase = true) }
@@ -137,7 +163,14 @@ private fun ChannelField(channel: String, paths: List<String>, onChange: (String
channel, { onChange(it); open = true }, singleLine = true, channel, { onChange(it); open = true }, singleLine = true,
label = { Text("Channel") }, label = { Text("Channel") },
placeholder = { Text("Default") }, placeholder = { Text("Default") },
trailingIcon = if (paths.isEmpty()) null else ({ ExposedDropdownMenuDefaults.TrailingIcon(expanded) }), trailingIcon = {
Row(verticalAlignment = Alignment.CenterVertically) {
IconButton(onClick = { current?.let(onChange) }, enabled = current != null) {
PackIcon(listOf("MAKE_CURRENT_CHANNEL_DEFAULT", "CHANNEL_SWITCH"), "This channel")
}
if (paths.isNotEmpty()) ExposedDropdownMenuDefaults.TrailingIcon(expanded)
}
},
modifier = Modifier.fillMaxWidth().menuAnchor(ExposedDropdownMenuAnchorType.PrimaryEditable), modifier = Modifier.fillMaxWidth().menuAnchor(ExposedDropdownMenuAnchorType.PrimaryEditable),
) )
ExposedDropdownMenu(expanded, { open = false }) { ExposedDropdownMenu(expanded, { open = false }) {
@@ -83,11 +83,12 @@ fun ChannelEditScreen(server: ServerController, edit: ChannelEdit, onDone: () ->
saving = true saving = true
scope.launch { scope.launch {
val trimmed = e.copy().apply { name = name.trim() } val trimmed = e.copy().apply { name = name.trim() }
val error = if (creating) server.createChannel(edit.parentId, trimmed) val saved = if (creating) server.createChannel(edit.parentId, trimmed)
else server.editChannel(edit.channelId, trimmed.changesFrom(o)) else server.editChannel(edit.channelId, trimmed.changesFrom(o))
saving = false saving = false
if (error == null) onDone() saved.onSuccess { onDone() }.onFailure {
else snackbar.showSnackbar((if (creating) "Could not create the channel: " else "Could not save the channel: ") + error) snackbar.showSnackbar((if (creating) "Could not create the channel: " else "Could not save the channel: ") + it.message)
}
} }
} }
@@ -153,6 +153,10 @@ fun ChannelTree(
listState: LazyListState = rememberLazyListState(), listState: LazyListState = rememberLazyListState(),
/** Brings our own client into view; its row may sit in folded channels. */ /** Brings our own client into view; its row may sit in folded channels. */
onShowSelf: () -> Unit = {}, onShowSelf: () -> Unit = {},
/** Clients picked to be moved or kicked together. */
selected: Set<Int> = emptySet(),
/** Picks a client into [selected]; null when there is nothing to do with several. */
onClientLongPress: ((ClientItem) -> Unit)? = null,
) { ) {
val rows = remember(tree, collapsed, currentChannel) { flatten(tree, collapsed, currentChannel) } val rows = remember(tree, collapsed, currentChannel) { flatten(tree, collapsed, currentChannel) }
var flashing by remember { mutableStateOf<TreeRef?>(null) } var flashing by remember { mutableStateOf<TreeRef?>(null) }
@@ -201,16 +205,17 @@ fun ChannelTree(
} }
items(rows, key = { it.key }) { row -> items(rows, key = { it.key }) { row ->
val background = rowBackground( val background = rowBackground(
when (row.ref) { when {
flashing -> FLASH row.ref == flashing -> FLASH
foundCurrent -> findCurrentColor() !row.ref.channel && row.ref.id in selected -> MaterialTheme.colorScheme.secondaryContainer
in found -> findMatchColor() row.ref == foundCurrent -> findCurrentColor()
row.ref in found -> findMatchColor()
else -> Color.Transparent else -> Color.Transparent
}, },
) )
when (row) { when (row) {
is TreeRow.Channel -> ChannelRow(row, background, onToggle, onChannel, onChannelDoubleTap) is TreeRow.Channel -> ChannelRow(row, background, onToggle, onChannel, onChannelDoubleTap)
is TreeRow.Client -> ClientRow(row, tree.countryFlags, background, onClient) is TreeRow.Client -> ClientRow(row, tree.countryFlags, background, onClient, onClientLongPress)
} }
} }
} }
@@ -239,6 +244,7 @@ private fun RowLayout(
/** The colour under [background], which a flash or find match goes over. */ /** The colour under [background], which a flash or find match goes over. */
tint: Color = Color.Transparent, tint: Color = Color.Transparent,
onDoubleClick: (() -> Unit)? = null, onDoubleClick: (() -> Unit)? = null,
onLongClick: (() -> Unit)? = null,
content: @Composable RowScope.() -> Unit, content: @Composable RowScope.() -> Unit,
) { ) {
Row( Row(
@@ -247,7 +253,7 @@ private fun RowLayout(
.background(tint) .background(tint)
.background(background) .background(background)
.height(ROW) .height(ROW)
.then(if (onClick != null) Modifier.combinedClickable(onDoubleClick = onDoubleClick, onClick = onClick) else Modifier) .then(if (onClick != null) Modifier.combinedClickable(onDoubleClick = onDoubleClick, onLongClick = onLongClick, onClick = onClick) else Modifier)
.padding(start = 4.dp + INDENT * depth, end = 8.dp), .padding(start = 4.dp + INDENT * depth, end = 8.dp),
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(4.dp), horizontalArrangement = Arrangement.spacedBy(4.dp),
@@ -315,9 +321,16 @@ private fun SpacerLabel(align: Char, caption: String, modifier: Modifier) {
} }
@Composable @Composable
private fun ClientRow(row: TreeRow.Client, countryFlags: Boolean, background: Color, onClient: (ClientItem) -> Unit) { private fun ClientRow(
row: TreeRow.Client,
countryFlags: Boolean,
background: Color,
onClient: (ClientItem) -> Unit,
onLongPress: ((ClientItem) -> Unit)?,
) {
val client = row.client val client = row.client
RowLayout(row.depth, onClick = { onClient(client) }, background = background, tint = Color(client.background)) { RowLayout(row.depth, onClick = { onClient(client) }, background = background, tint = Color(client.background),
onLongClick = onLongPress?.let { { it(client) } }) {
Spacer(Modifier.width(ICON + 4.dp)) Spacer(Modifier.width(ICON + 4.dp))
StatusIcon(client.status) StatusIcon(client.status)
Row(Modifier.weight(1f), horizontalArrangement = Arrangement.spacedBy(4.dp)) { Row(Modifier.weight(1f), horizontalArrangement = Arrangement.spacedBy(4.dp)) {
@@ -337,7 +350,11 @@ private fun ClientRow(row: TreeRow.Client, countryFlags: Boolean, background: Co
color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
} }
} }
// TeamSpeak's order: talk power ahead of the groups, a talk request after them.
if (client.talker) PackIcon("IS_TALKER", "Talk power granted", size = ICON)
else if (client.lacksTalkPower) PackIcon("INPUT_MUTED", "Insufficient talk power", size = ICON)
for (id in client.groupIconIds) ServerIcon(id, size = ICON) for (id in client.groupIconIds) ServerIcon(id, size = ICON)
if (client.talkRequest) PackIcon("TALK_POWER_REQUEST", "Talk power requested", size = ICON)
// The country's flag comes last, at the row's edge. // The country's flag comes last, at the row's edge.
if (countryFlags) CountryFlag(client.country) if (countryFlags) CountryFlag(client.country)
} }
@@ -5,6 +5,7 @@ import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.size
@@ -29,7 +30,6 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.runtime.key
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.snapshotFlow import androidx.compose.runtime.snapshotFlow
@@ -49,11 +49,11 @@ import androidx.compose.ui.input.key.type
import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.android.ChatKey
import eu.lixko.ts3j.client.android.ChatLine import eu.lixko.ts3j.client.android.ChatLine
import eu.lixko.ts3j.client.android.ChatMatch import eu.lixko.ts3j.client.android.ChatMatch
import eu.lixko.ts3j.client.android.Chats import eu.lixko.ts3j.client.android.Chats
import eu.lixko.ts3j.client.android.Conversation import eu.lixko.ts3j.client.android.Conversation
import eu.lixko.ts3j.client.chat.ChatKey
import eu.lixko.ts3j.client.text.TextQuery import eu.lixko.ts3j.client.text.TextQuery
import kotlinx.coroutines.flow.drop import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.filter
@@ -65,7 +65,7 @@ fun ChatPane(
selected: Conversation, selected: Conversation,
canSend: Boolean, canSend: Boolean,
onSelect: (ChatKey) -> Unit, onSelect: (ChatKey) -> Unit,
onClose: (ChatKey.Private) -> Unit, onClose: (ChatKey) -> Unit,
onSend: (String) -> Unit, onSend: (String) -> Unit,
/** Picks a file to share in [selected]. */ /** Picks a file to share in [selected]. */
onAttach: () -> Unit, onAttach: () -> Unit,
@@ -79,9 +79,23 @@ fun ChatPane(
/** A line to scroll to. */ /** A line to scroll to. */
reveal: Long? = null, reveal: Long? = null,
onRevealed: () -> Unit = {}, onRevealed: () -> Unit = {},
/** Whether a swipe over the lines goes to the neighbouring conversation. */
swipeTabs: Boolean = false,
/** For the lines, such as a swipe out of the chat. */
linesModifier: Modifier = Modifier,
) { ) {
Column(modifier) { Column(modifier) {
val tabs = rememberLazyListState()
// A conversation picked by other means than its chip, such as a swipe, comes into view.
LaunchedEffect(selected.key) {
val index = chats.all.indexOfFirst { it.key == selected.key }
val info = tabs.layoutInfo
if (index >= 0 && info.visibleItemsInfo.none { it.index == index && it.offset >= 0 && it.offset + it.size <= info.viewportEndOffset }) {
tabs.animateScrollToItem(index)
}
}
LazyRow( LazyRow(
state = tabs,
contentPadding = PaddingValues(horizontal = 8.dp), contentPadding = PaddingValues(horizontal = 8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp),
) { ) {
@@ -89,8 +103,20 @@ fun ChatPane(
ConversationChip(conversation, conversation.key == selected.key, onSelect, onClose) ConversationChip(conversation, conversation.key == selected.key, onSelect, onClose)
} }
} }
// Each conversation opens at its newest line. val swipe = rememberSwipeState()
key(selected.key) { Lines(lines, onLink, Modifier.weight(1f), find, current, reveal, onRevealed) } SwipeHost(
swipe, selected.key,
neighbour = { key, dir ->
if (!swipeTabs) null
else chats.all.indexOfFirst { it.key == key }.takeIf { it >= 0 }?.let { chats.all.getOrNull(it + dir)?.key }
},
onSwipe = onSelect,
modifier = Modifier.weight(1f).then(linesModifier).swipeSource(swipe),
) { key ->
// Each conversation opens at its newest line; the one beside it while swiping shows all of its own.
if (key == selected.key) Lines(lines, onLink, Modifier.fillMaxSize(), find, current, reveal, onRevealed)
else chats[key]?.let { Lines(it.lines, onLink, Modifier.fillMaxSize(), TextQuery.EMPTY, null, null) {} }
}
// One unsent message per conversation, kept while another one is on screen. // One unsent message per conversation, kept while another one is on screen.
val drafts = rememberSaveable(saver = DraftsSaver) { mutableStateMapOf<String, String>() } val drafts = rememberSaveable(saver = DraftsSaver) { mutableStateMapOf<String, String>() }
val draftKey = selected.key.toString() val draftKey = selected.key.toString()
@@ -136,7 +162,7 @@ private fun ConversationChip(
conversation: Conversation, conversation: Conversation,
selected: Boolean, selected: Boolean,
onSelect: (ChatKey) -> Unit, onSelect: (ChatKey) -> Unit,
onClose: (ChatKey.Private) -> Unit, onClose: (ChatKey) -> Unit,
) { ) {
val key = conversation.key val key = conversation.key
FilterChip( FilterChip(
@@ -144,7 +170,7 @@ private fun ConversationChip(
onClick = { onSelect(key) }, onClick = { onSelect(key) },
label = { Text(conversation.title, maxLines = 1, overflow = TextOverflow.Ellipsis) }, label = { Text(conversation.title, maxLines = 1, overflow = TextOverflow.Ellipsis) },
leadingIcon = if (conversation.unread) ({ Badge() }) else null, leadingIcon = if (conversation.unread) ({ Badge() }) else null,
trailingIcon = if (key is ChatKey.Private) ({ trailingIcon = if (key.isPrivate) ({
Icon(Icons.Filled.Close, "Close", Modifier.size(18.dp).clickable { onClose(key) }) Icon(Icons.Filled.Close, "Close", Modifier.size(18.dp).clickable { onClose(key) })
}) else null, }) else null,
) )
@@ -5,6 +5,7 @@ import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Image import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
@@ -15,18 +16,17 @@ import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.layout.Box
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.Button import androidx.compose.material3.Button
import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuAnchorType
import androidx.compose.material3.ExposedDropdownMenuBox import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.ExposedDropdownMenuAnchorType
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.IconButton import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem import androidx.compose.material3.ListItem
import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme
@@ -50,12 +50,15 @@ import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.BookmarkManager
import eu.lixko.ts3j.client.android.IdentityInfo import eu.lixko.ts3j.client.android.IdentityInfo
import eu.lixko.ts3j.client.android.IdentityManager
import eu.lixko.ts3j.client.android.MyTeamSpeakAccount
import eu.lixko.ts3j.client.android.SessionController import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.config.Bookmark import eu.lixko.ts3j.client.config.Bookmark
import eu.lixko.ts3j.client.net.IconRepository import eu.lixko.ts3j.client.net.IconRepository
@@ -64,7 +67,10 @@ import eu.lixko.ts3j.client.net.IconRepository
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
fun ConnectScreen( fun ConnectScreen(
vm: SessionController, sessions: SessionController,
bookmarkManager: BookmarkManager,
identityManager: IdentityManager,
account: MyTeamSpeakAccount,
snackbar: SnackbarHostState, snackbar: SnackbarHostState,
onSettings: () -> Unit, onSettings: () -> Unit,
onMyTeamSpeak: () -> Unit, onMyTeamSpeak: () -> Unit,
@@ -73,13 +79,13 @@ fun ConnectScreen(
/** Back to the servers already connected; null when there are none. */ /** Back to the servers already connected; null when there are none. */
onBack: (() -> Unit)?, onBack: (() -> Unit)?,
) { ) {
val lastEnd by vm.lastEnd.collectAsStateWithLifecycle() val lastEnd by sessions.lastEnd.collectAsStateWithLifecycle()
val bookmarks by vm.bookmarks.collectAsStateWithLifecycle() val bookmarks by bookmarkManager.all.collectAsStateWithLifecycle()
val identities by vm.identities.all.collectAsStateWithLifecycle() val identities by identityManager.all.collectAsStateWithLifecycle()
val myTeamSpeakSignedIn by vm.myTeamSpeakSignedIn.collectAsStateWithLifecycle() val myTeamSpeakSignedIn by account.signedIn.collectAsStateWithLifecycle()
var address by rememberSaveable { mutableStateOf(vm.lastAddress) } var address by rememberSaveable { mutableStateOf(sessions.lastAddress) }
var identityId by rememberSaveable { mutableStateOf("") } var identityId by rememberSaveable { mutableStateOf("") }
var nickname by rememberSaveable { mutableStateOf(vm.nicknameFor("")) } var nickname by rememberSaveable { mutableStateOf(identityManager.nicknameFor("")) }
var password by rememberSaveable { mutableStateOf("") } var password by rememberSaveable { mutableStateOf("") }
if (onBack != null) BackHandler(onBack = onBack) if (onBack != null) BackHandler(onBack = onBack)
@@ -115,18 +121,18 @@ fun ConnectScreen(
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password)) keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password))
IdentityField(identities, identityId) { IdentityField(identities, identityId) {
identityId = it identityId = it
nickname = vm.nicknameFor(it) nickname = identityManager.nicknameFor(it)
} }
lastEnd?.let { lastEnd?.let {
Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodyMedium) Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodyMedium)
} }
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Button( Button(
onClick = { onConnect { vm.connect(address.trim(), nickname.trim(), password, identityId) } }, onClick = { onConnect { sessions.connect(address.trim(), nickname.trim(), password, identityId) } },
enabled = address.isNotBlank() && nickname.isNotBlank(), enabled = address.isNotBlank() && nickname.isNotBlank(),
) { Text("Connect") } ) { Text("Connect") }
TextButton(onClick = { TextButton(onClick = {
onEditBookmark(BookmarkEdit(-1, vm.newBookmark(address.trim(), nickname.trim(), password, identityId))) onEditBookmark(BookmarkEdit(-1, bookmarkManager.newBookmark(address.trim(), nickname.trim(), password, identityId)))
}, enabled = address.isNotBlank()) { Text("Add bookmark") } }, enabled = address.isNotBlank()) { Text("Add bookmark") }
} }
} }
@@ -144,10 +150,10 @@ fun ConnectScreen(
} }
} }
itemsIndexed(bookmarks) { index, bookmark -> itemsIndexed(bookmarks) { index, bookmark ->
BookmarkRow(bookmark, identities, { onConnect { vm.connect(bookmark) } }, BookmarkRow(bookmark, identities, { onConnect { sessions.connect(bookmark) } },
onEdit = { onEditBookmark(BookmarkEdit(index, bookmark)) }, onEdit = { onEditBookmark(BookmarkEdit(index, bookmark)) },
onPin = if (vm.canPinShortcuts) ({ vm.pinShortcut(bookmark) }) else null, onPin = if (bookmarkManager.canPinShortcuts) ({ bookmarkManager.pinShortcut(bookmark) }) else null,
onRemove = { vm.removeBookmark(bookmark) }) onRemove = { bookmarkManager.remove(bookmark) })
} }
} }
} }
@@ -40,14 +40,14 @@ import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.SessionController import eu.lixko.ts3j.client.android.ContactManager
import eu.lixko.ts3j.client.contacts.Contact import eu.lixko.ts3j.client.contacts.Contact
import eu.lixko.ts3j.client.contacts.ContactDefaults import eu.lixko.ts3j.client.contacts.ContactDefaults
import eu.lixko.ts3j.client.contacts.ContactType import eu.lixko.ts3j.client.contacts.ContactType
import eu.lixko.ts3j.client.contacts.NicknameDisplay import eu.lixko.ts3j.client.contacts.NicknameDisplay
import kotlinx.coroutines.launch
import java.time.format.DateTimeFormatter import java.time.format.DateTimeFormatter
import kotlin.math.roundToInt import kotlin.math.roundToInt
import kotlinx.coroutines.launch
private val SEEN = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm") private val SEEN = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
@@ -70,20 +70,20 @@ private val GROUPS = listOf(
* @param editing the unique id of the contact whose page is open, if any * @param editing the unique id of the contact whose page is open, if any
*/ */
@Composable @Composable
fun ContactsScreen(vm: SessionController, editing: String?, onEdit: (String?) -> Unit, onBack: () -> Unit) { fun ContactsScreen(contacts: ContactManager, editing: String?, onEdit: (String?) -> Unit, onBack: () -> Unit) {
var defaults by rememberSaveable { mutableStateOf(false) } var defaults by rememberSaveable { mutableStateOf(false) }
when { when {
editing != null -> return ContactScreen(vm, editing, onBack = { onEdit(null) }) editing != null -> return ContactScreen(contacts, editing, onBack = { onEdit(null) })
defaults -> return ContactDefaultsScreen(vm, onBack = { defaults = false }) defaults -> return ContactDefaultsScreen(contacts, onBack = { defaults = false })
} }
val contacts by vm.contacts.collectAsStateWithLifecycle() val all by contacts.all.collectAsStateWithLifecycle()
val scope = rememberCoroutineScope() val scope = rememberCoroutineScope()
var menu by remember { mutableStateOf(false) } var menu by remember { mutableStateOf(false) }
var imported by remember { mutableStateOf<String?>(null) } var imported by remember { mutableStateOf<String?>(null) }
val importer = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> val importer = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri != null) scope.launch { if (uri != null) scope.launch {
imported = runCatching { vm.importContacts(uri) }.fold( imported = runCatching { contacts.import(uri) }.fold(
{ (found, added) -> { (found, added) ->
if (found == 0) "That file holds no contacts." if (found == 0) "That file holds no contacts."
else "Imported $found contacts, $added of them new." else "Imported $found contacts, $added of them new."
@@ -107,21 +107,21 @@ fun ContactsScreen(vm: SessionController, editing: String?, onEdit: (String?) ->
}) { padding -> }) { padding ->
LazyColumn(Modifier.padding(padding)) { LazyColumn(Modifier.padding(padding)) {
imported?.let { item { Hint(it) } } imported?.let { item { Hint(it) } }
if (contacts.isEmpty()) { if (all.isEmpty()) {
item { item {
Hint("No contacts yet. Tap a client on a server to add them as a friend or block them, " + Hint("No contacts yet. Tap a client on a server to add them as a friend or block them, " +
"or import the contacts of TeamSpeak 3 from its settings.db.") "or import the contacts of TeamSpeak 3 from its settings.db.")
} }
} }
for ((type, title) in GROUPS) { for ((type, title) in GROUPS) {
val group = contacts.filter { it.type == type }.sortedBy { label(it).lowercase() } val group = all.filter { it.type == type }.sortedBy { label(it).lowercase() }
if (group.isEmpty()) continue if (group.isEmpty()) continue
item(key = type) { Section(title) } item(key = type) { Section(title) }
items(group, key = { it.uniqueId }) { contact -> items(group, key = { it.key() }) { contact ->
ListItem( ListItem(
headlineContent = { Text(label(contact), color = typeColor(contact.type)) }, headlineContent = { Text(label(contact), color = typeColor(contact.type)) },
supportingContent = { Text(lastSeen(contact)) }, supportingContent = { Text(lastSeen(contact)) },
modifier = Modifier.clickable { onEdit(contact.uniqueId) }, modifier = Modifier.clickable { onEdit(contact.key()) },
) )
} }
} }
@@ -131,16 +131,18 @@ fun ContactsScreen(vm: SessionController, editing: String?, onEdit: (String?) ->
/** One contact's settings; each is stored as it is changed, the names once the page is left. */ /** One contact's settings; each is stored as it is changed, the names once the page is left. */
@Composable @Composable
private fun ContactScreen(vm: SessionController, uniqueId: String, onBack: () -> Unit) { private fun ContactScreen(contacts: ContactManager, uniqueId: String, onBack: () -> Unit) {
val contacts by vm.contacts.collectAsStateWithLifecycle() val all by contacts.all.collectAsStateWithLifecycle()
val contact = contacts.firstOrNull { it.uniqueId == uniqueId } // A client's unique id may stand for a contact filed under its myTeamSpeak ID.
val key = remember(uniqueId) { contacts.find(uniqueId)?.key() ?: uniqueId }
val contact = all.firstOrNull { it.key() == key }
if (contact == null) { if (contact == null) {
LaunchedEffect(Unit) { onBack() } LaunchedEffect(Unit) { onBack() }
return return
} }
// Starts from the stored entry, which may have been seen again since this page opened. // Starts from the stored entry, which may have been seen again since this page opened.
fun edit(change: Contact.() -> Unit) { fun edit(change: Contact.() -> Unit) {
vm.contact(uniqueId)?.let { vm.saveContact(it.apply(change)) } contacts.find(key)?.let { contacts.save(it.apply(change)) }
} }
var customName by rememberSaveable(uniqueId) { mutableStateOf(contact.nickname) } var customName by rememberSaveable(uniqueId) { mutableStateOf(contact.nickname) }
var phoneticName by rememberSaveable(uniqueId) { mutableStateOf(contact.phoneticNickname) } var phoneticName by rememberSaveable(uniqueId) { mutableStateOf(contact.phoneticNickname) }
@@ -191,10 +193,11 @@ private fun ContactScreen(vm: SessionController, uniqueId: String, onBack: () ->
Section("Details") Section("Details")
val context = LocalContext.current val context = LocalContext.current
LinkRow("Unique ID", contact.uniqueId) { val idLabel = if (contact.uniqueId.isEmpty()) "myTeamSpeak ID" else "Unique ID"
LinkRow(idLabel, contact.shownId()) {
// The system confirms the copy itself. // The system confirms the copy itself.
context.getSystemService(ClipboardManager::class.java) context.getSystemService(ClipboardManager::class.java)
.setPrimaryClip(ClipData.newPlainText("Unique ID", contact.uniqueId)) .setPrimaryClip(ClipData.newPlainText(idLabel, contact.shownId()))
} }
ListItem(headlineContent = { Text(lastSeen(contact)) }) ListItem(headlineContent = { Text(lastSeen(contact)) })
} }
@@ -208,7 +211,7 @@ private fun ContactScreen(vm: SessionController, uniqueId: String, onBack: () ->
confirmButton = { confirmButton = {
TextButton(onClick = { TextButton(onClick = {
removing = false removing = false
vm.removeContact(uniqueId) contacts.remove(key)
onBack() onBack()
}) { Text("Remove") } }) { Text("Remove") }
}, },
@@ -219,14 +222,14 @@ private fun ContactScreen(vm: SessionController, uniqueId: String, onBack: () ->
/** What a client starts out with when added as a friend, blocked or neutral. */ /** What a client starts out with when added as a friend, blocked or neutral. */
@Composable @Composable
private fun ContactDefaultsScreen(vm: SessionController, onBack: () -> Unit) { private fun ContactDefaultsScreen(contacts: ContactManager, onBack: () -> Unit) {
val defaults = vm.settings.contactDefaults val defaults = contacts.defaults
var tab by rememberSaveable { mutableStateOf(ContactType.FRIEND) } var tab by rememberSaveable { mutableStateOf(ContactType.FRIEND) }
var entry by remember(tab) { mutableStateOf(ContactDefaults.Entry().apply { copyFrom(defaults.of(tab)) }) } var entry by remember(tab) { mutableStateOf(ContactDefaults.Entry().apply { copyFrom(defaults.of(tab)) }) }
fun edit(change: ContactDefaults.Entry.() -> Unit) { fun edit(change: ContactDefaults.Entry.() -> Unit) {
val changed = ContactDefaults.Entry().apply { copyFrom(entry); change() } val changed = ContactDefaults.Entry().apply { copyFrom(entry); change() }
defaults.of(tab).copyFrom(changed) defaults.of(tab).copyFrom(changed)
vm.settings.save() contacts.saveDefaults()
entry = changed entry = changed
} }
@@ -251,7 +254,7 @@ private fun ContactDefaultsScreen(vm: SessionController, onBack: () -> Unit) {
} }
} }
private fun label(contact: Contact) = contact.nickname.ifBlank { contact.uniqueId } private fun label(contact: Contact) = contact.label()
private fun lastSeen(contact: Contact): String { private fun lastSeen(contact: Contact): String {
val seen = contact.lastSeen ?: return "Never seen" val seen = contact.lastSeen ?: return "Never seen"
@@ -78,10 +78,9 @@ fun FilesScreen(server: ServerController, channelId: Int, channelName: String, p
LaunchedEffect(uploadedHere) { if (uploadedHere > 0) reloads++ } LaunchedEffect(uploadedHere) { if (uploadedHere > 0) reloads++ }
val tell = { message: String -> scope.launch { snackbar.showSnackbar(message) }; Unit } val tell = { message: String -> scope.launch { snackbar.showSnackbar(message) }; Unit }
val act = { call: suspend () -> String? -> val act = { call: suspend () -> Result<Unit> ->
scope.launch { scope.launch {
val error = call() call().onSuccess { reloads++ }.onFailure { snackbar.showSnackbar(it.message ?: it.javaClass.simpleName) }
if (error != null) snackbar.showSnackbar(error) else reloads++
} }
Unit Unit
} }
@@ -37,7 +37,7 @@ import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.android.ClientItem import eu.lixko.ts3j.client.android.ClientItem
import eu.lixko.ts3j.client.android.ServerController import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.net.GroupChoice import eu.lixko.ts3j.client.net.GroupChoice
import eu.lixko.ts3j.client.net.TeamspeakConnection import eu.lixko.ts3j.client.net.ClientAdmin
import eu.lixko.ts3j.client.net.ban.BanRule import eu.lixko.ts3j.client.net.ban.BanRule
import eu.lixko.ts3j.client.net.ban.BanUnit import eu.lixko.ts3j.client.net.ban.BanUnit
@@ -48,7 +48,7 @@ fun KickPrompt(title: String, onDismiss: () -> Unit, onKick: (String) -> Unit) {
AlertDialog( AlertDialog(
onDismissRequest = onDismiss, onDismissRequest = onDismiss,
title = { Text(title) }, title = { Text(title) },
text = { LimitedField(reason, { reason = it }, "Reason", TeamspeakConnection.KICK_REASON_LIMIT) }, text = { LimitedField(reason, { reason = it }, "Reason", ClientAdmin.KICK_REASON_LIMIT) },
confirmButton = { TextButton(onClick = { onKick(reason.trim()) }) { Text("Kick") } }, confirmButton = { TextButton(onClick = { onKick(reason.trim()) }) { Text("Kick") } },
dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
) )
@@ -182,28 +182,54 @@ fun GroupsDialog(
) )
} }
/** The kicks, the ban and the groups of [client], as far as we may use them; [onDone] once one went out. */ /**
* Talk power, the kicks, the ban and the groups of [client], as far as we may use them; [onDone] once one went out.
* Null when there is none of them.
*/
@Composable @Composable
fun ClientModeration(server: ServerController, client: ClientItem, onDone: () -> Unit) { fun clientModeration(server: ServerController, client: ClientItem, onDone: () -> Unit): (@Composable () -> Unit)? {
val serverGroups = remember(client) { server.serverGroupChoices(client.id) }
val channelGroups = remember(client) { server.channelGroupChoices(client.id) }
val kickChannel = !client.self && server.permissions.canKickFromChannel()
val kickServer = !client.self && server.permissions.canKickFromServer()
val ban = !client.self && server.permissions.canBanClients()
val talker = server.permissions.canGrantTalkPower() && (client.talker || client.lacksTalkPower)
val showServerGroups = serverGroups.any { it.allowed() }
val showChannelGroups = channelGroups.any { it.allowed() && !it.assigned() }
if (!(talker || kickChannel || kickServer || ban || showServerGroups || showChannelGroups)) return null
return {
ClientModeration(server, client, serverGroups, channelGroups, talker, kickChannel, kickServer, ban,
showServerGroups, showChannelGroups, onDone)
}
}
@Composable
private fun ClientModeration(
server: ServerController,
client: ClientItem,
serverGroups: List<GroupChoice>,
channelGroups: List<GroupChoice>,
talker: Boolean,
kickChannel: Boolean,
kickServer: Boolean,
ban: Boolean,
showServerGroups: Boolean,
showChannelGroups: Boolean,
onDone: () -> Unit,
) {
var kick by remember { mutableStateOf<Boolean?>(null) } var kick by remember { mutableStateOf<Boolean?>(null) }
var banning by remember { mutableStateOf(false) } var banning by remember { mutableStateOf(false) }
var groups by remember { mutableStateOf<Boolean?>(null) } var groups by remember { mutableStateOf<Boolean?>(null) }
val serverGroups = remember(client) { server.serverGroupChoices(client.id) }
val channelGroups = remember(client) { server.channelGroupChoices(client.id) }
if (!client.self) { if (talker) {
if (server.canKickFromChannel) Action("KICK_FROM_CHANNEL", "Kick from channel") { kick = false } if (client.talker) Action("TALK_POWER_REVOKE", "Revoke talk power") { server.setTalker(listOf(client.id), false); onDone() }
if (server.canKickFromServer) Action("KICK_FROM_SERVER", "Kick from server") { kick = true } else Action("TALK_POWER_GRANT", "Grant talk power") { server.setTalker(listOf(client.id), true); onDone() }
if (server.canBanClients) Action("BAN_CLIENT", "Ban") { banning = true }
}
val showServerGroups = serverGroups.any { it.allowed() }
val showChannelGroups = channelGroups.any { it.allowed() && !it.assigned() }
if (showServerGroups || showChannelGroups) {
Row {
if (showServerGroups) Action("PERMISSIONS_SERVER_GROUPS", "Server groups", Modifier.weight(1f)) { groups = true }
if (showChannelGroups) Action("PERMISSIONS_CHANNEL_GROUPS", "Channel group", Modifier.weight(1f)) { groups = false }
}
} }
if (kickChannel) Action("KICK_FROM_CHANNEL", "Kick from channel") { kick = false }
if (kickServer) Action("KICK_FROM_SERVER", "Kick from server") { kick = true }
if (ban) Action("BAN_CLIENT", "Ban") { banning = true }
if (showServerGroups) Action("PERMISSIONS_SERVER_GROUPS", "Server groups") { groups = true }
if (showChannelGroups) Action("PERMISSIONS_CHANNEL_GROUPS", "Channel group") { groups = false }
kick?.let { fromServer -> kick?.let { fromServer ->
KickPrompt( KickPrompt(
@@ -211,12 +237,12 @@ fun ClientModeration(server: ServerController, client: ClientItem, onDone: () ->
onDismiss = { kick = null }, onDismiss = { kick = null },
) { reason -> ) { reason ->
kick = null kick = null
if (fromServer) server.kickFromServer(client.id, reason) else server.kickFromChannel(client.id, reason) if (fromServer) server.kickFromServer(listOf(client.id), reason) else server.kickFromChannel(listOf(client.id), reason)
onDone() onDone()
} }
} }
if (banning) { if (banning) {
BanPrompt(client.name, server.maxBanSeconds, onDismiss = { banning = false }) { seconds, reason -> BanPrompt(client.name, server.permissions.maxBanSeconds(), onDismiss = { banning = false }) { seconds, reason ->
banning = false banning = false
server.ban(client.id, seconds, reason) server.ban(client.id, seconds, reason)
onDone() onDone()
@@ -42,28 +42,30 @@ import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.android.SessionController import eu.lixko.ts3j.client.android.MyTeamSpeakAccount
import eu.lixko.ts3j.client.config.Bookmark import eu.lixko.ts3j.client.config.Bookmark
import eu.lixko.ts3j.client.myts.AccountInfo import eu.lixko.ts3j.client.myts.AccountInfo
import eu.lixko.ts3j.client.myts.MyTeamSpeak import eu.lixko.ts3j.client.myts.MyTeamSpeak
import eu.lixko.ts3j.client.myts.MyTeamSpeakSync
import eu.lixko.ts3j.client.myts.MyTsException import eu.lixko.ts3j.client.myts.MyTsException
import eu.lixko.ts3j.client.teamspeak.SyncItem import eu.lixko.ts3j.client.teamspeak.SyncItem
import kotlinx.coroutines.launch import eu.lixko.ts3j.client.teamspeak.TeamSpeakImporter
import java.io.IOException import java.io.IOException
import java.time.ZoneId import java.time.ZoneId
import java.time.format.DateTimeFormatter import java.time.format.DateTimeFormatter
import java.time.format.FormatStyle import java.time.format.FormatStyle
import kotlinx.coroutines.launch
private data class ItemRow(val item: SyncItem, val imported: Boolean, val selected: Boolean) private data class ItemRow(val item: SyncItem, val imported: Boolean, val selected: Boolean)
/** /**
* The myTeamSpeak account: sign in and out, and pick what the account synchronises to * The myTeamSpeak account: sign in and out, pick what the account synchronises to import,
* import. Signing in lasts until signing out; the password itself is not kept. * or synchronise both ways. Signing in lasts until signing out; the password itself is not kept.
*/ */
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
fun MyTeamSpeakScreen(vm: SessionController, onBack: () -> Unit) { fun MyTeamSpeakScreen(account: MyTeamSpeakAccount, onBack: () -> Unit) {
val login = vm.myTeamSpeak val login = account.login
val scope = rememberCoroutineScope() val scope = rememberCoroutineScope()
var signedIn by remember { mutableStateOf(login.isSignedIn) } var signedIn by remember { mutableStateOf(login.isSignedIn) }
var busy by remember { mutableStateOf(false) } var busy by remember { mutableStateOf(false) }
@@ -74,16 +76,16 @@ fun MyTeamSpeakScreen(vm: SessionController, onBack: () -> Unit) {
var info by remember { mutableStateOf<AccountInfo?>(null) } var info by remember { mutableStateOf<AccountInfo?>(null) }
var all by remember { mutableStateOf(emptyList<SyncItem>()) } var all by remember { mutableStateOf(emptyList<SyncItem>()) }
var rows by remember { mutableStateOf(emptyList<ItemRow>()) } var rows by remember { mutableStateOf(emptyList<ItemRow>()) }
BackHandler(onBack = onBack) var conflicted by remember { mutableStateOf<MyTeamSpeakSync.Plan?>(null) }
fun show(account: MyTeamSpeak.Account) { fun show(fetched: MyTeamSpeak.Account) {
info = account.info() info = fetched.info()
all = account.items() all = fetched.items()
rows = all.filter { it !is SyncItem.Folder }.map { rows = all.filter { it !is SyncItem.Folder && (it !is SyncItem.Contact || TeamSpeakImporter.isImportable(it)) }.map {
val imported = vm.isImported(it) val imported = account.isImported(it)
ItemRow(it, imported, !imported) ItemRow(it, imported, !imported)
} }
message = if (rows.isEmpty()) "The account holds no bookmarks or identities." else null message = if (rows.isEmpty()) "The account holds no bookmarks, identities or contacts." else null
error = false error = false
} }
@@ -106,10 +108,26 @@ fun MyTeamSpeakScreen(vm: SessionController, onBack: () -> Unit) {
} }
} }
LaunchedEffect(Unit) { suspend fun finishSync(plan: MyTeamSpeakSync.Plan) {
if (signedIn) work { show(vm.fetchMyTeamSpeak()) } val r = account.finishSync(plan)
rows = rows.map { it.copy(imported = account.isImported(it.item)) }
message = if (r.sent() == 0 && r.received() == 0) "In sync."
else "Synchronized: ${r.sent()} sent, ${r.received()} received."
} }
LaunchedEffect(Unit) {
if (signedIn) work { show(account.fetch()) }
}
conflicted?.let { plan ->
SyncConflictsScreen(plan.conflicts()) { accepted ->
conflicted = null
if (accepted) work { finishSync(plan) } else message = "Synchronization cancelled."
}
return
}
BackHandler(onBack = onBack)
Scaffold( Scaffold(
topBar = { topBar = {
TopAppBar( TopAppBar(
@@ -117,7 +135,7 @@ fun MyTeamSpeakScreen(vm: SessionController, onBack: () -> Unit) {
navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } }, navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } },
actions = { actions = {
if (signedIn) { if (signedIn) {
IconButton(onClick = { work { show(vm.fetchMyTeamSpeak()) } }, enabled = !busy) { IconButton(onClick = { work { show(account.fetch()) } }, enabled = !busy) {
PackIcon("REFRESH", "Refresh") PackIcon("REFRESH", "Refresh")
} }
} }
@@ -134,7 +152,7 @@ fun MyTeamSpeakScreen(vm: SessionController, onBack: () -> Unit) {
if (!signedIn) { if (!signedIn) {
item { item {
Column(Modifier.padding(horizontal = 16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { Column(Modifier.padding(horizontal = 16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text("Sign in to bring over the bookmarks and identities your account synchronises. " + Text("Sign in to bring over the bookmarks, identities and contacts your account synchronises. " +
"The app stays signed in; your password itself is not kept.") "The app stays signed in; your password itself is not kept.")
OutlinedTextField(email, { email = it }, Modifier.fillMaxWidth(), label = { Text("Email") }, OutlinedTextField(email, { email = it }, Modifier.fillMaxWidth(), label = { Text("Email") },
singleLine = true, enabled = !busy, singleLine = true, enabled = !busy,
@@ -145,7 +163,7 @@ fun MyTeamSpeakScreen(vm: SessionController, onBack: () -> Unit) {
Button( Button(
onClick = { onClick = {
work { work {
show(vm.signInMyTeamSpeak(email.trim(), password)) show(account.signIn(email.trim(), password))
password = "" password = ""
} }
}, },
@@ -162,7 +180,7 @@ fun MyTeamSpeakScreen(vm: SessionController, onBack: () -> Unit) {
color = MaterialTheme.colorScheme.onSurfaceVariant) color = MaterialTheme.colorScheme.onSurfaceVariant)
} }
OutlinedButton(onClick = { OutlinedButton(onClick = {
scope.launch { vm.signOutMyTeamSpeak() } scope.launch { account.signOut() }
signedIn = false signedIn = false
rows = emptyList() rows = emptyList()
all = emptyList() all = emptyList()
@@ -189,6 +207,7 @@ fun MyTeamSpeakScreen(vm: SessionController, onBack: () -> Unit) {
for ((title, section) in listOf( for ((title, section) in listOf(
"Identities" to rows.filter { it.item is SyncItem.Identity }, "Identities" to rows.filter { it.item is SyncItem.Identity },
"Bookmarks" to rows.filter { it.item is SyncItem.Bookmark }, "Bookmarks" to rows.filter { it.item is SyncItem.Bookmark },
"Contacts" to rows.filter { it.item is SyncItem.Contact },
)) { )) {
if (section.isEmpty()) continue if (section.isEmpty()) continue
item { item {
@@ -212,21 +231,32 @@ fun MyTeamSpeakScreen(vm: SessionController, onBack: () -> Unit) {
) )
} }
} }
if (rows.isNotEmpty()) {
item { item {
Row(Modifier.padding(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
if (rows.isNotEmpty()) {
Button( Button(
onClick = { onClick = {
work { work {
val r = vm.importMyTeamSpeak(all, rows.filter { it.selected }.map { it.item }) val r = account.import(all, rows.filter { it.selected }.map { it.item })
rows = rows.map { it.copy(imported = vm.isImported(it.item), selected = false) } rows = rows.map { it.copy(imported = account.isImported(it.item), selected = false) }
message = "Imported ${count(r.identitiesAdded(), "identity", "identities")} and " + message = "Imported ${count(r.identitiesAdded(), "identity", "identities")}, " +
"${count(r.bookmarksAdded(), "bookmark", "bookmarks")}." "${count(r.bookmarksAdded(), "bookmark", "bookmarks")} and " +
"${count(r.contactsAdded(), "contact", "contacts")}."
} }
}, },
enabled = !busy && rows.any { it.selected }, enabled = !busy && rows.any { it.selected },
modifier = Modifier.padding(horizontal = 16.dp),
) { Text("Import selected") } ) { Text("Import selected") }
} }
OutlinedButton(
onClick = {
work {
val plan = account.planSync()
if (plan.conflicts().isEmpty()) finishSync(plan) else conflicted = plan
}
},
enabled = !busy,
) { Text("Synchronize") }
}
} }
} }
message?.let { text -> message?.let { text ->
@@ -253,12 +283,14 @@ private fun Detail(label: String, value: String) {
private fun name(item: SyncItem) = when (item) { private fun name(item: SyncItem) = when (item) {
is SyncItem.Bookmark -> item.name().ifBlank { item.address() } is SyncItem.Bookmark -> item.name().ifBlank { item.address() }
is SyncItem.Identity -> item.name() is SyncItem.Identity -> item.name()
is SyncItem.Contact -> item.customName().ifBlank { item.myTeamSpeakId() }
else -> "" else -> ""
} }
private fun details(item: SyncItem) = when (item) { private fun details(item: SyncItem) = when (item) {
is SyncItem.Bookmark -> Bookmark.hostPort(item.address(), item.port()) is SyncItem.Bookmark -> Bookmark.hostPort(item.address(), item.port())
is SyncItem.Identity -> item.nickname() is SyncItem.Identity -> item.nickname()
is SyncItem.Contact -> item.myTeamSpeakId()
else -> "" else -> ""
} }
@@ -12,6 +12,7 @@ import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.android.SessionController import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.config.Setting
import eu.lixko.ts3j.client.config.Settings import eu.lixko.ts3j.client.config.Settings
import kotlin.math.abs import kotlin.math.abs
import kotlin.math.roundToInt import kotlin.math.roundToInt
@@ -21,58 +22,57 @@ private const val MAX_BITRATE_KBITS = 160f
/** What voice costs and survives on the wire: the encoder, duplicate packets and receive buffering. */ /** What voice costs and survives on the wire: the encoder, duplicate packets and receive buffering. */
@Composable @Composable
fun NetworkSettingsScreen(vm: SessionController, onBack: () -> Unit) { fun NetworkSettingsScreen(settings: Settings, sessions: SessionController, onBack: () -> Unit) {
val settings = vm.settings fun <T> change(setting: Setting<T>, value: T) {
fun change(edit: Settings.() -> Unit) { setting.set(value)
settings.edit() sessions.applySettings()
vm.applySettings()
} }
var vbr by remember { mutableStateOf(settings.vbr) } var vbr by remember { mutableStateOf(settings.vbr.get()) }
var fec by remember { mutableStateOf(settings.fec) } var fec by remember { mutableStateOf(settings.fec.get()) }
var music by remember { mutableStateOf(settings.music) } var music by remember { mutableStateOf(settings.music.get()) }
var redundancy by remember { mutableStateOf(settings.redundancyDelay) } var redundancy by remember { mutableStateOf(settings.redundancyDelay.get()) }
var copies by remember { mutableStateOf(settings.redundancyCopies) } var copies by remember { mutableStateOf(settings.redundancyCopies.get()) }
var receiveBuffer by remember { mutableStateOf(settings.receiveBuffer) } var receiveBuffer by remember { mutableStateOf(settings.receiveBuffer.get()) }
SubScreen("Network", onBack) { padding -> SubScreen("Network", onBack) { padding ->
Column(Modifier.padding(padding).verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) { Column(Modifier.padding(padding).verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) {
Section("Encoder") Section("Encoder")
Level("Bitrate", settings.bitrate / 1000f, MIN_BITRATE_KBITS..MAX_BITRATE_KBITS, { "${it.roundToInt()} kbit/s" }) { Level("Bitrate", settings.bitrate.get() / 1000f, MIN_BITRATE_KBITS..MAX_BITRATE_KBITS, { "${it.roundToInt()} kbit/s" }) {
change { bitrate = it.roundToInt() * 1000 } change(settings.bitrate, it.roundToInt() * 1000)
} }
Toggle("Variable bitrate (VBR)", vbr) { Toggle("Variable bitrate (VBR)", vbr) {
vbr = it vbr = it
change { this.vbr = it } change(settings.vbr, it)
} }
Toggle("Forward error correction (FEC)", fec) { Toggle("Forward error correction (FEC)", fec) {
fec = it fec = it
change { this.fec = it } change(settings.fec, it)
} }
Level("Complexity", settings.complexity.toFloat(), 0f..10f, { "${it.roundToInt()}" }, steps = 9) { Level("Complexity", settings.complexity.get().toFloat(), 0f..10f, { "${it.roundToInt()}" }, steps = 9) {
change { complexity = it.roundToInt() } change(settings.complexity, it.roundToInt())
} }
Toggle("Music codec (stereo, higher fidelity)", music) { Toggle("Music codec (stereo, higher fidelity)", music) {
music = it music = it
change { this.music = it } change(settings.music, it)
} }
Section("Redundancy") Section("Redundancy")
ChoiceLevel("Delay", Settings.REDUNDANCY_DELAYS, redundancy) { ChoiceLevel("Delay", Settings.REDUNDANCY_DELAYS, redundancy) {
redundancy = it redundancy = it
change { redundancyDelay = it } change(settings.redundancyDelay, it)
} }
if (redundancy > 0) { if (redundancy > 0) {
Level("Copies", copies.toFloat(), 1f..Settings.MAX_REDUNDANCY_COPIES.toFloat(), { "${it.roundToInt()}" }, Level("Copies", copies.toFloat(), 1f..Settings.MAX_REDUNDANCY_COPIES.toFloat(), { "${it.roundToInt()}" },
steps = Settings.MAX_REDUNDANCY_COPIES - 2) { steps = Settings.MAX_REDUNDANCY_COPIES - 2) {
copies = it.roundToInt() copies = it.roundToInt()
change { redundancyCopies = copies } change(settings.redundancyCopies, copies)
} }
} }
Section("Receive") Section("Receive")
ChoiceLevel("Extra buffering", Settings.RECEIVE_BUFFERS, receiveBuffer) { ChoiceLevel("Extra buffering", Settings.RECEIVE_BUFFERS, receiveBuffer) {
receiveBuffer = it receiveBuffer = it
change { this.receiveBuffer = it } change(settings.receiveBuffer, it)
} }
} }
} }
@@ -79,8 +79,8 @@ fun PictureViewerHost(server: ServerController, content: @Composable () -> Unit)
PictureViewer( PictureViewer(
picture, picture,
onSteal = if (picture.ownAvatar) null else { data -> onSteal = if (picture.ownAvatar) null else { data ->
val error = server.setAvatar(data) val message = server.setAvatar(data).fold({ "Avatar set." }, { it.message })
Toast.makeText(context, error ?: "Avatar set.", Toast.LENGTH_SHORT).show() Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
}, },
onDismiss = { viewed = null }, onDismiss = { viewed = null },
) )
@@ -31,8 +31,8 @@ import kotlinx.coroutines.flow.MutableStateFlow
internal class PttTarget(val owner: ServerController?, val state: SessionState, val talking: Boolean) internal class PttTarget(val owner: ServerController?, val state: SessionState, val talking: Boolean)
@Composable @Composable
internal fun rememberPttTarget(vm: SessionController): PttTarget { internal fun rememberPttTarget(sessions: SessionController): PttTarget {
val owner by vm.micOwner.collectAsStateWithLifecycle() val owner by sessions.micOwner.collectAsStateWithLifecycle()
val state by remember(owner) { owner?.state ?: MutableStateFlow(SessionState()) }.collectAsStateWithLifecycle() val state by remember(owner) { owner?.state ?: MutableStateFlow(SessionState()) }.collectAsStateWithLifecycle()
val tree by remember(owner) { owner?.tree ?: MutableStateFlow(ServerTree()) }.collectAsStateWithLifecycle() val tree by remember(owner) { owner?.tree ?: MutableStateFlow(ServerTree()) }.collectAsStateWithLifecycle()
val self = tree.client(state.selfClientId) val self = tree.client(state.selfClientId)
@@ -78,12 +78,12 @@ internal fun PushToTalk(
/** Nothing but a push-to-talk button, as big as the screen; it talks in any input mode. */ /** Nothing but a push-to-talk button, as big as the screen; it talks in any input mode. */
@Composable @Composable
fun GiantPttScreen(vm: SessionController, onBack: () -> Unit) { fun GiantPttScreen(sessions: SessionController, onBack: () -> Unit) {
val target = rememberPttTarget(vm) val target = rememberPttTarget(sessions)
SubScreen("Giant PTT", onBack) { padding -> SubScreen("Giant PTT", onBack) { padding ->
val fill = Modifier.padding(padding).fillMaxSize().padding(16.dp) val fill = Modifier.padding(padding).fillMaxSize().padding(16.dp)
if (target.owner != null && target.state.connected) { if (target.owner != null && target.state.connected) {
PushToTalk(target.talking, vm::setForceTransmit, fill, RoundedCornerShape(32.dp), PushToTalk(target.talking, sessions::setForceTransmit, fill, RoundedCornerShape(32.dp),
MaterialTheme.typography.displaySmall) MaterialTheme.typography.displaySmall)
} else { } else {
Box(fill, contentAlignment = Alignment.Center) { Box(fill, contentAlignment = Alignment.Center) {
@@ -0,0 +1,126 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.State
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import eu.lixko.ts3j.client.android.ChatMatch
import eu.lixko.ts3j.client.android.Conversation
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.android.ServerTree
import eu.lixko.ts3j.client.android.TreeFind
import eu.lixko.ts3j.client.android.findIn
/** The channel tree as it shows under the find bar: what of it, which rows are folded, and the match it is on. */
@Stable
internal class TreeView(
private val server: ServerController,
private val source: State<ServerTree>,
private val collapsedSource: State<Set<Int>>,
private val find: FindState,
) {
val treeFind by derivedStateOf { TreeFind(find.usable, find.channels) }
val filtering by derivedStateOf { find.filter && !treeFind.query.isEmpty }
val tree by derivedStateOf { if (filtering) source.value.only(treeFind) else source.value }
val hits by derivedStateOf { source.value.hits(treeFind) }
val found by derivedStateOf { hits.mapTo(HashSet()) { TreeRef(treeFind.channels, it) } }
/** The match the tree is on. */
private var at by mutableStateOf<Int?>(null)
val current: TreeRef? get() = at?.takeIf { it in hits }?.let { TreeRef(treeFind.channels, it) }
val position: Int get() = hits.indexOf(at) + 1
/** A row to bring into view. */
var reveal by mutableStateOf<TreeRef?>(null)
// While the tree is filtered every channel opens, so every match shows; folding one then lasts as long as the filter.
private var folded by mutableStateOf(Folded(null, emptySet()))
private val filterFolded: Set<Int> get() = folded.ids.takeIf { folded.find == treeFind }.orEmpty()
val collapsed: Set<Int> get() = if (filtering) filterFolded else collapsedSource.value
private data class Folded(val find: TreeFind?, val ids: Set<Int>)
fun toggle(channelId: Int) {
if (!filtering) server.toggleCollapsed(channelId)
else if (channelId in filterFolded) folded = Folded(treeFind, filterFolded - channelId)
else folded = Folded(treeFind, filterFolded + channelId)
}
/** Opens the channels down to [ref] and brings it into view. */
fun show(ref: TreeRef) {
val tree = source.value
val path = (if (ref.channel) tree.parentsOf(ref.id) else tree.pathTo(ref.id)).orEmpty()
if (filtering) folded = Folded(treeFind, filterFolded - path.toSet()) else server.expand(path)
reveal = ref
}
private fun showHit(id: Int) {
at = id
show(TreeRef(treeFind.channels, id))
}
/** For a new search: on the first match while the tree is on screen, else on none. */
fun restart(onScreen: Boolean) {
at = null
if (onScreen) hits.firstOrNull()?.let(::showHit)
}
fun step(delta: Int) {
if (hits.isNotEmpty()) showHit(hits[next(hits.indexOf(at), delta, hits.size)])
}
}
@Composable
internal fun rememberTreeView(
server: ServerController,
tree: State<ServerTree>,
collapsed: State<Set<Int>>,
find: FindState,
): TreeView = remember(server, tree, collapsed, find) { TreeView(server, tree, collapsed, find) }
/** A conversation as it shows under the find bar: its lines, and the match it is on. */
@Stable
internal class ChatSearch(private val conversation: State<Conversation>, private val find: FindState) {
val query get() = find.usable
val lines by derivedStateOf {
val all = conversation.value.lines
if (find.filter && !query.isEmpty) all.filter { query.matches(it.plain) } else all
}
val hits by derivedStateOf { findIn(lines, query, MAX_CHAT_MATCHES) }
val capped: Boolean get() = hits.size == MAX_CHAT_MATCHES
/** The match the chat is on. */
var at by mutableStateOf<ChatMatch?>(null)
private set
val position: Int get() = hits.indexOf(at) + 1
/** A line to bring into view. */
var reveal by mutableStateOf<Long?>(null)
/** For a new search: on the newest match while the chat is on screen, else on none. */
fun restart(onScreen: Boolean) {
at = if (onScreen) hits.lastOrNull() else null
reveal = at?.line
}
fun step(delta: Int) {
if (hits.isEmpty()) return
at = hits[next(hits.indexOf(at), delta, hits.size)]
reveal = at?.line
}
}
@Composable
internal fun rememberChatSearch(conversation: State<Conversation>, find: FindState): ChatSearch =
remember(conversation, find) { ChatSearch(conversation, find) }
/** More matches than this nobody steps through one by one. */
private const val MAX_CHAT_MATCHES = 5000
/** The index [delta] on from [at] among [size], wrapping around; from none, the first or the last. */
private fun next(at: Int, delta: Int, size: Int): Int =
if (at < 0) (if (delta > 0) 0 else size - 1) else Math.floorMod(at + delta, size)
@@ -0,0 +1,105 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.listSaver
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import eu.lixko.ts3j.client.chat.ChatKey
import eu.lixko.ts3j.client.chat.ChatScope
import eu.lixko.ts3j.client.config.WhisperList
/** What fills a server's screen: its tree and chat, or a page of its own. */
internal sealed interface ServerPage {
data object Main : ServerPage
data object BanList : ServerPage
data object WhisperLists : ServerPage
data class EditChannel(val edit: ChannelEdit) : ServerPage
/** A channel's files, with the password the channel takes. */
data class Files(val channelId: Int, val name: String, val password: String) : ServerPage
data class ConnectionInfo(val clientId: Int) : ServerPage
}
/** A sheet or dialog over the tree and chat; one at a time. */
internal sealed interface Overlay {
data object None : Overlay
data object Server : Overlay
/** [fromTree] when it was opened from the tree rather than a link. */
data class Client(val id: Int, val fromTree: Boolean) : Overlay
data class Channel(val id: Int) : Overlay
/** A locked channel being joined, while its password is asked for. */
data class JoinLocked(val channelId: Int) : Overlay
/** A locked channel whose files are wanted, while its password is asked for. */
data class FilesLocked(val channelId: Int) : Overlay
data class DeleteChannel(val id: Int) : Overlay
/** Kicking the clients picked in the tree: from the server, or from their channels. */
data class Kick(val fromServer: Boolean) : Overlay
/** Something being added to a whisper list, while the list is picked: its name and how to add it. */
class AddToWhisperList(val name: String, val add: (WhisperList) -> Unit) : Overlay
}
/** Where a server's screen is: on which page, the tree or the chat, and what is over it. */
@Stable
internal class ServerNav(page: ServerPage = ServerPage.Main, showChat: Boolean = false, chatKey: ChatKey = ChatKey.CHANNEL) {
var page by mutableStateOf(page)
var showChat by mutableStateOf(showChat)
/** The conversation the chat shows. */
var chatKey by mutableStateOf(chatKey)
var overlay by mutableStateOf<Overlay>(Overlay.None)
fun openChat(key: ChatKey) {
chatKey = key
showChat = true
}
fun back() {
page = ServerPage.Main
}
fun dismiss() {
overlay = Overlay.None
}
companion object {
// Sheets and dialogs are not kept: they would come back over a tree that has moved on.
val Saver = listSaver<ServerNav, Any>(
save = { listOf(it.showChat, saveKey(it.chatKey)) + savePage(it.page) },
restore = { ServerNav(restorePage(it.drop(2)), it[0] as Boolean, restoreKey(it[1] as String)) },
)
private fun saveKey(key: ChatKey) = when (key.scope()) {
ChatScope.SERVER -> "server"
ChatScope.CHANNEL -> "channel"
ChatScope.PRIVATE -> "private:${key.clientId()}"
}
private fun restoreKey(saved: String) = when {
saved == "server" -> ChatKey.SERVER
saved.startsWith("private:") -> ChatKey.privateWith(saved.substringAfter(':').toInt())
else -> ChatKey.CHANNEL
}
private fun savePage(page: ServerPage): List<Any> = when (page) {
ServerPage.Main -> listOf("main")
ServerPage.BanList -> listOf("bans")
ServerPage.WhisperLists -> listOf("whisper")
is ServerPage.EditChannel -> listOf("edit", page.edit.channelId, page.edit.parentId)
is ServerPage.Files -> listOf("files", page.channelId, page.name, page.password)
is ServerPage.ConnectionInfo -> listOf("info", page.clientId)
}
private fun restorePage(saved: List<Any>): ServerPage = when (saved[0]) {
"bans" -> ServerPage.BanList
"whisper" -> ServerPage.WhisperLists
"edit" -> ServerPage.EditChannel(ChannelEdit(saved[1] as Int, saved[2] as Int))
"files" -> ServerPage.Files(saved[1] as Int, saved[2] as String, saved[3] as String)
"info" -> ServerPage.ConnectionInfo(saved[1] as Int)
else -> ServerPage.Main
}
}
}
@Composable
internal fun rememberServerNav(): ServerNav = rememberSaveable(saver = ServerNav.Saver) { ServerNav() }
@@ -0,0 +1,167 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.ChannelItem
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.android.ServerTree
import eu.lixko.ts3j.client.android.SessionState
import eu.lixko.ts3j.client.android.WhisperListManager
import kotlinx.coroutines.launch
/** Joins [channel], asking for its password first when it is locked. */
internal fun ServerNav.join(server: ServerController, channel: ChannelItem) {
if (channel.locked) overlay = Overlay.JoinLocked(channel.id) else server.joinChannel(channel.id)
}
/** The sheet or dialog [ServerNav.overlay] names; a sheet goes with its client or channel when that leaves the tree. */
@Composable
internal fun ServerOverlay(
nav: ServerNav,
whisperLists: WhisperListManager,
server: ServerController,
state: SessionState,
tree: ServerTree,
treeView: TreeView,
picking: TreePicking,
snackbar: SnackbarHostState,
onLink: (String) -> Unit,
onEditContact: (String) -> Unit,
onEditBookmark: (BookmarkEdit) -> Unit,
) {
val infoUpdates by server.infoUpdates.collectAsStateWithLifecycle()
val can = server.permissions
// Out here: the dialog leaves the composition, and would take its scope along, before the deletion fails.
val scope = rememberCoroutineScope()
val dismiss = nav::dismiss
/** Closes the overlay, then does [action]. */
fun then(action: () -> Unit): () -> Unit = { dismiss(); action() }
when (val o = nav.overlay) {
Overlay.None -> {}
Overlay.Server -> remember(tree, infoUpdates) { server.serverDetails() }?.let {
ServerSheet(it, onLink, onDismiss = dismiss,
onBookmark = then { server.bookmark(state.channelId)?.let { b -> onEditBookmark(BookmarkEdit(-1, b)) } },
onBanList = if (can.canViewBanList()) then { nav.page = ServerPage.BanList } else null,
onCreateChannel = if (can.canCreateChannels()) then { nav.page = ServerPage.EditChannel(ChannelEdit(0, 0)) } else null)
}
is Overlay.Client -> {
val id = o.id
LaunchedEffect(id) { server.requestClientDetails(id) }
tree.client(id)?.let { client ->
ClientSheet(
client = client,
details = remember(id, tree, infoUpdates) { server.clientDetails(id) },
onLink = onLink,
away = state.away,
initialVolume = remember(id) { server.clientVolume(id) },
onDismiss = dismiss,
onMessage = then { nav.openChat(server.openPrivateChat(id)) },
onPoke = { server.poke(id, it); dismiss() },
onVolume = { server.setClientVolume(id, it) },
onAway = { server.setAway(it); dismiss() },
onTalkRequest = if (client.self && (client.talkRequest || server.canRequestTalkPower)) {
{ server.setTalkRequest(it); dismiss() }
} else null,
onAddContact = { server.addContact(id, it) },
onEditContact = then { onEditContact(client.uniqueId) },
onConnectionInfo = then { nav.page = ServerPage.ConnectionInfo(id) },
onWhisper = if (state.whisperControls) then { server.whisperToClient(id) } else null,
onAddToWhisperList = if (state.whisperControls) then {
server.clientRef(id)?.let { ref -> nav.overlay = Overlay.AddToWhisperList(client.name) { it.clients.add(ref) } }
} else null,
onMove = if (can.canMoveClients()) then { picking.moving = setOf(id) } else null,
onMoveToOwnChannel = if (can.canMoveClients() && tree.channel(state.channelId)?.clients?.none { it.id == id } == true) {
then { server.moveClients(listOf(id), state.channelId) }
} else null,
onFindInTree = if (o.fromTree) null else then {
nav.showChat = false
treeView.show(TreeRef(false, id))
},
moderation = clientModeration(server, client, dismiss),
)
}
}
is Overlay.Channel -> {
val id = o.id
LaunchedEffect(id) { server.requestChannelDetails(id) }
tree.channel(id)?.let { channel ->
ChannelSheet(
channel = channel,
details = remember(id, tree, infoUpdates) { server.channelDetails(id) },
onLink = onLink,
current = id == state.channelId,
onDismiss = dismiss,
onJoin = then { nav.join(server, channel) },
onSubscribe = { server.setSubscribed(id, it); dismiss() },
onWhisper = if (state.whisperControls) then { server.whisperToChannel(id) } else null,
onAddToWhisperList = if (state.whisperControls) then {
server.channelRef(id)?.let { ref -> nav.overlay = Overlay.AddToWhisperList(channel.name) { it.channels.add(ref) } }
} else null,
onFiles = if (can.canBrowseFiles()) then {
if (channel.locked) nav.overlay = Overlay.FilesLocked(id)
else nav.page = ServerPage.Files(id, channel.name, "")
} else null,
onCreateSub = if (can.canCreateChannels()) then { nav.page = ServerPage.EditChannel(ChannelEdit(0, id)) } else null,
onEdit = if (can.canEditChannels()) then { nav.page = ServerPage.EditChannel(ChannelEdit(id)) } else null,
onDelete = if (can.canDeleteChannels()) then { nav.overlay = Overlay.DeleteChannel(id) } else null,
)
}
}
is Overlay.Kick -> {
val others = picking.kickable(o.fromServer)
val whom = others.singleOrNull()?.let { tree.client(it)?.name } ?: "${others.size} clients"
KickPrompt(
if (o.fromServer) "Kick $whom from the server?" else "Kick $whom from the channel?",
onDismiss = dismiss,
) { reason ->
dismiss()
picking.kick(o.fromServer, reason)
}
}
is Overlay.JoinLocked -> TextPrompt(
title = "Join ${tree.channel(o.channelId)?.name.orEmpty()}",
label = "Channel password",
confirm = "Join",
password = true,
onDismiss = dismiss,
onConfirm = { dismiss(); server.joinChannel(o.channelId, it) },
)
is Overlay.FilesLocked -> TextPrompt(
title = "Files of ${tree.channel(o.channelId)?.name.orEmpty()}",
label = "Channel password",
confirm = "Open",
password = true,
onDismiss = dismiss,
onConfirm = { dismiss(); nav.page = ServerPage.Files(o.channelId, tree.channel(o.channelId)?.name.orEmpty(), it) },
)
is Overlay.DeleteChannel -> {
val channel = tree.channel(o.id)
AlertDialog(
onDismissRequest = dismiss,
title = { Text("Delete ${channel?.name.orEmpty()}?") },
text = if (channel != null && (channel.children.isNotEmpty() || channel.clients.isNotEmpty())) {
{ Text("Its sub-channels go with it, and whoever is in it is moved out.") }
} else null,
confirmButton = {
TextButton(onClick = then {
scope.launch { server.deleteChannel(o.id).onFailure { snackbar.showSnackbar("Could not delete the channel: ${it.message}") } }
}) { Text("Delete") }
},
dismissButton = { TextButton(onClick = dismiss) { Text("Cancel") } },
)
}
is Overlay.AddToWhisperList -> AddToWhisperListDialog(whisperLists, o.name, onDismiss = dismiss) { index, newName ->
dismiss()
whisperLists.addTo(index, newName, o.add)
}
}
}
@@ -1,125 +1,56 @@
package eu.lixko.ts3j.client.android.ui package eu.lixko.ts3j.client.android.ui
import android.widget.Toast
import androidx.activity.compose.BackHandler import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.consumeWindowInsets import androidx.compose.foundation.layout.consumeWindowInsets
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Badge
import androidx.compose.material3.BadgedBox
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton import androidx.compose.material3.IconButton
import androidx.compose.material3.IconToggleButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MenuDefaults
import androidx.compose.material3.Scaffold import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBar
import androidx.compose.material3.minimumInteractiveComponentSize
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.input.key.Key import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.key.KeyEventType import androidx.compose.ui.input.key.KeyEventType
import androidx.compose.ui.input.key.isCtrlPressed import androidx.compose.ui.input.key.isCtrlPressed
import androidx.compose.ui.input.key.key import androidx.compose.ui.input.key.key
import androidx.compose.ui.input.key.onPreviewKeyEvent import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.compose.ui.input.key.type import androidx.compose.ui.input.key.type
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalUriHandler import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.LifecycleResumeEffect import androidx.lifecycle.compose.LifecycleResumeEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.ChannelItem import eu.lixko.ts3j.client.android.MyTeamSpeakAccount
import eu.lixko.ts3j.client.android.ChatKey
import eu.lixko.ts3j.client.android.ChatMatch
import eu.lixko.ts3j.client.android.ServerController import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.android.SessionController import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.android.SessionState import eu.lixko.ts3j.client.android.SwipePrefs
import eu.lixko.ts3j.client.android.TreeFind import eu.lixko.ts3j.client.android.TreeSwipe
import eu.lixko.ts3j.client.android.findIn import eu.lixko.ts3j.client.android.WhisperListManager
import eu.lixko.ts3j.client.config.Settings import eu.lixko.ts3j.client.chat.ChatKey
import eu.lixko.ts3j.client.config.WhisperList import eu.lixko.ts3j.client.config.BanReasonPresets
import eu.lixko.ts3j.client.myts.ChatAttachment import eu.lixko.ts3j.client.myts.ChatAttachment
import eu.lixko.ts3j.client.session.ServerLink import eu.lixko.ts3j.client.session.ServerLink
import eu.lixko.ts3j.client.text.TsLink import eu.lixko.ts3j.client.text.TsLink
import kotlinx.coroutines.launch
private val ChatKeySaver = Saver<ChatKey, String>(
save = { key ->
when (key) {
ChatKey.Server -> "server"
ChatKey.Channel -> "channel"
is ChatKey.Private -> "private:${key.clientId}"
}
},
restore = { saved ->
when {
saved == "server" -> ChatKey.Server
saved.startsWith("private:") -> ChatKey.Private(saved.substringAfter(':').toInt())
else -> ChatKey.Channel
}
},
)
private val ChannelEditSaver = Saver<ChannelEdit?, IntArray>(
save = { edit -> edit?.let { intArrayOf(it.channelId, it.parentId) } },
restore = { ChannelEdit(it[0], it[1]) },
)
/** A channel whose files are browsed, with the password they take. */
private data class FilesOf(val channelId: Int, val name: String, val password: String)
private val FilesOfSaver = Saver<FilesOf?, List<Any>>(
save = { f -> f?.let { listOf(it.channelId, it.name, it.password) } },
restore = { FilesOf(it[0] as Int, it[1] as String, it[2] as String) },
)
/** A connection: the channel tree and the chat, with the voice controls underneath. */ /** A connection: the channel tree and the chat, with the voice controls underneath. */
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
fun ServerScreen( fun ServerScreen(
vm: SessionController, sessions: SessionController,
whisperLists: WhisperListManager,
account: MyTeamSpeakAccount,
swipe: SwipePrefs,
banReasons: BanReasonPresets,
server: ServerController, server: ServerController,
snackbar: SnackbarHostState, snackbar: SnackbarHostState,
onSettings: () -> Unit, onSettings: () -> Unit,
@@ -128,140 +59,78 @@ fun ServerScreen(
onEnableMicrophone: () -> Unit, onEnableMicrophone: () -> Unit,
onConnectOther: () -> Unit, onConnectOther: () -> Unit,
onEditBookmark: (BookmarkEdit) -> Unit, onEditBookmark: (BookmarkEdit) -> Unit,
/** Turns to another server, for a swipe over the tree. */
serverSwipe: SwipeState? = null,
/** False for a server beside the one on show while swiping to it. */
active: Boolean = true,
) { ) {
val state by server.state.collectAsStateWithLifecycle() val sessionState = server.state.collectAsStateWithLifecycle()
val tree by server.tree.collectAsStateWithLifecycle() val state by sessionState
val chats by server.chats.collectAsStateWithLifecycle() val treeState = server.tree.collectAsStateWithLifecycle()
val collapsed by server.collapsed.collectAsStateWithLifecycle() val tree by treeState
val chatsState = server.chats.collectAsStateWithLifecycle()
val chats by chatsState
var showChat by rememberSaveable { mutableStateOf(false) } val nav = rememberServerNav()
// Out here, so the tree keeps its place while the chat or another screen replaces it. // Out here, so the tree keeps its place while the chat or another page replaces it.
val treeList = rememberLazyListState() val treeList = rememberLazyListState()
var chatKey by rememberSaveable(stateSaver = ChatKeySaver) { mutableStateOf<ChatKey>(ChatKey.Channel) } val conversationState = remember(chatsState, nav) { derivedStateOf { chatsState.value[nav.chatKey] ?: chatsState.value.channel } }
val conversation = chats[chatKey] ?: chats.channel val conversation by conversationState
var clientSheet by remember { mutableStateOf<Int?>(null) } val picking = rememberTreePicking(server, treeState, sessionState)
var clientSheetFromTree by remember { mutableStateOf(false) }
/** A row to show in the tree. */ val treeSwipe by swipe.tree.collectAsStateWithLifecycle()
var reveal by remember { mutableStateOf<TreeRef?>(null) } val chatTabSwipe by swipe.chatTabs.collectAsStateWithLifecycle()
var channelSheet by remember { mutableStateOf<Int?>(null) } // The chat lies to the right of the tree.
/** A locked channel being joined, while its password is asked for. */ val chatBesideTree = treeSwipe == TreeSwipe.CHAT
var joinLocked by remember { mutableStateOf<Int?>(null) } val pageSwipe = rememberSwipeState()
val join = { channel: ChannelItem ->
if (channel.locked) joinLocked = channel.id else server.joinChannel(channel.id)
}
var serverSheet by remember { mutableStateOf(false) }
val bookmarkHere = { channelId: Int -> server.bookmark(channelId)?.let { onEditBookmark(BookmarkEdit(-1, it)) } }
var banList by rememberSaveable { mutableStateOf(false) }
var channelEdit by rememberSaveable(stateSaver = ChannelEditSaver) { mutableStateOf<ChannelEdit?>(null) }
var files by rememberSaveable(stateSaver = FilesOfSaver) { mutableStateOf<FilesOf?>(null) }
/** A locked channel whose files are wanted, while its password is asked for. */
var filesLocked by remember { mutableStateOf<Int?>(null) }
var deletingChannel by remember { mutableStateOf<Int?>(null) }
var whisperLists by rememberSaveable { mutableStateOf(false) }
/** What is being added to a whisper list, while the list is picked: its name and how to add it. */
var toWhisperList by remember { mutableStateOf<Pair<String, (WhisperList) -> Unit>?>(null) }
var connectionInfo by rememberSaveable { mutableStateOf<Int?>(null) }
/** The client to move, while a channel for them is being picked. */
var moving by remember { mutableStateOf<Int?>(null) }
val infoUpdates by server.infoUpdates.collectAsStateWithLifecycle()
val chatRequest by server.chatRequest.collectAsStateWithLifecycle() val chatRequest by server.chatRequest.collectAsStateWithLifecycle()
LaunchedEffect(chatRequest) { LaunchedEffect(chatRequest) {
val key = chatRequest ?: return@LaunchedEffect val key = chatRequest ?: return@LaunchedEffect
chatKey = if (chats[key] != null) key else server.openPrivateChat(key.clientId) nav.openChat(if (chats[key] != null) key else server.openPrivateChat(key.clientId))
showChat = true
server.chatRequestHandled() server.chatRequestHandled()
} }
val viewing = if (showChat) conversation.key else null val viewing = if (nav.showChat) conversation.key else null
LifecycleResumeEffect(viewing) { LifecycleResumeEffect(viewing, active) {
server.viewing = viewing if (active) server.viewing = viewing
onPauseOrDispose { server.viewing = null } onPauseOrDispose { server.viewing = null }
} }
val uriHandler = LocalUriHandler.current val uriHandler = LocalUriHandler.current
val attachments = rememberAttachmentActions(vm, server, snackbar, conversation.key) val attachments = rememberAttachmentActions(account, server, snackbar, conversation.key)
val onLink: (String) -> Unit = { href -> val onLink: (String) -> Unit = { href ->
val ref = TsLink.parse(href) val ref = TsLink.parse(href)
when { when {
ChatAttachment.isHref(href) -> attachments.open(href) ChatAttachment.isHref(href) -> attachments.open(href)
ServerLink.isLink(href) -> ServerLink.parse(href)?.let { vm.open(it) } ServerLink.isLink(href) -> ServerLink.parse(href)?.let { sessions.open(it) }
ref == null -> runCatching { uriHandler.openUri(href) } ref == null -> runCatching { uriHandler.openUri(href) }
ref.client -> { clientSheet = ref.id; clientSheetFromTree = false } ref.client -> nav.overlay = Overlay.Client(ref.id, fromTree = false)
else -> channelSheet = ref.id else -> nav.overlay = Overlay.Channel(ref.id)
} }
} }
// Find: in the tree, clients or channels; in the chat, the conversation on screen. // Find: in the tree, clients or channels; in the chat, the conversation on screen.
val find = rememberSaveable(saver = FindState.Saver) { FindState() } val find = rememberSaveable(saver = FindState.Saver) { FindState() }
val treeFind = TreeFind(find.usable, find.channels) val treeView = rememberTreeView(server, treeState, server.collapsed.collectAsStateWithLifecycle(), find)
val treeHits = remember(tree, treeFind) { tree.hits(treeFind) } val chatSearch = rememberChatSearch(conversationState, find)
val treeFiltering = find.filter && !treeFind.query.isEmpty LaunchedEffect(treeView.treeFind, nav.showChat) { treeView.restart(onScreen = !nav.showChat) }
val shownTree = remember(tree, treeFind, treeFiltering) { if (treeFiltering) tree.only(treeFind) else tree } LaunchedEffect(chatSearch.query, conversation.key, find.filter, nav.showChat) { chatSearch.restart(onScreen = nav.showChat) }
// While the tree is filtered every channel opens, so every match shows; folding one then lasts as long as the filter.
var filterCollapsed by remember(treeFiltering, treeFind) { mutableStateOf(emptySet<Int>()) } when (val page = nav.page) {
/** The match the tree is on. */ ServerPage.Main -> {}
var treeAt by remember { mutableStateOf<Int?>(null) } ServerPage.BanList -> return BanListScreen(server, banReasons, onBack = nav::back)
// Lambdas, not local functions: Compose remembers a reference to a local function with what it first captured. ServerPage.WhisperLists -> return WhisperListsScreen(whisperLists, server, onBack = nav::back)
val showTreeHit = { id: Int? -> is ServerPage.EditChannel -> return ChannelEditScreen(server, page.edit, onDone = nav::back)
if (id != null) { is ServerPage.Files -> return FilesScreen(server, page.channelId, page.name, page.password, onBack = nav::back)
treeAt = id is ServerPage.ConnectionInfo -> return ConnectionInfoScreen(server, page.clientId, tree.client(page.clientId), onBack = nav::back)
val path = (if (treeFind.channels) tree.parentsOf(id) else tree.pathTo(id)).orEmpty()
if (treeFiltering) filterCollapsed = filterCollapsed - path.toSet() else server.expand(path)
reveal = TreeRef(treeFind.channels, id)
}
}
LaunchedEffect(treeFind, showChat) {
treeAt = null
if (!showChat) showTreeHit(treeHits.firstOrNull())
} }
val chatQuery = find.usable val onTree = !nav.showChat
val chatLines = remember(conversation.lines, chatQuery, find.filter) { BackHandler(active && nav.showChat) { nav.showChat = false }
if (find.filter && !chatQuery.isEmpty) conversation.lines.filter { chatQuery.matches(it.plain) } else conversation.lines BackHandler(active && onTree && picking.moving != null) { picking.moving = null }
} BackHandler(active && onTree && picking.moving == null && picking.selection.isNotEmpty()) { picking.clear() }
val chatHits = remember(chatLines, chatQuery) { findIn(chatLines, chatQuery, MAX_CHAT_MATCHES) } BackHandler(active && find.open) { find.open = false }
/** The match the chat is on; a new search starts from the newest. */
var chatAt by remember { mutableStateOf<ChatMatch?>(null) }
var chatReveal by remember { mutableStateOf<Long?>(null) }
LaunchedEffect(chatQuery, conversation.key, find.filter, showChat) {
chatAt = if (showChat) chatHits.lastOrNull() else null
chatReveal = chatAt?.line
}
val step = { delta: Int ->
if (showChat && chatHits.isNotEmpty()) {
chatAt = chatHits[next(chatHits.indexOf(chatAt), delta, chatHits.size)]
chatReveal = chatAt?.line
} else if (!showChat && treeHits.isNotEmpty()) {
showTreeHit(treeHits[next(treeHits.indexOf(treeAt), delta, treeHits.size)])
}
}
if (banList) {
BanListScreen(server, vm.banReasons, onBack = { banList = false })
return
}
channelEdit?.let {
ChannelEditScreen(server, it, onDone = { channelEdit = null })
return
}
files?.let {
FilesScreen(server, it.channelId, it.name, it.password, onBack = { files = null })
return
}
if (whisperLists) {
WhisperListsScreen(vm, server, onBack = { whisperLists = false })
return
}
connectionInfo?.let { id ->
ConnectionInfoScreen(server, id, tree.client(id), onBack = { connectionInfo = null })
return
}
BackHandler(showChat) { showChat = false }
BackHandler(moving != null && !showChat) { moving = null }
BackHandler(find.open) { find.open = false }
Scaffold( Scaffold(
// A hardware keyboard's Ctrl+F, as on the desktop. // A hardware keyboard's Ctrl+F, as on the desktop.
@@ -272,19 +141,18 @@ fun ServerScreen(
}, },
topBar = { topBar = {
if (find.open) { if (find.open) {
if (showChat) { if (nav.showChat) {
FindBar(find, inTree = false, chatHits.indexOf(chatAt) + 1, chatHits.size, FindBar(find, inTree = false, chatSearch.position, chatSearch.hits.size, chatSearch.capped, chatSearch::step)
chatHits.size == MAX_CHAT_MATCHES, step)
} else { } else {
FindBar(find, inTree = true, treeHits.indexOf(treeAt) + 1, treeHits.size, false, step) FindBar(find, inTree = true, treeView.position, treeView.hits.size, false, treeView::step)
} }
} else { } else {
TopAppBar( TopAppBar(
title = { ServerSwitcher(vm, server, state, onConnectOther) }, title = { ServerSwitcher(sessions, server, state, onConnectOther) },
expandedHeight = 48.dp, expandedHeight = 48.dp,
actions = { actions = {
state.hostButton?.let { HostButtonAction(it) { url -> runCatching { uriHandler.openUri(url) } } } state.hostButton?.let { HostButtonAction(it) { url -> runCatching { uriHandler.openUri(url) } } }
if (state.connected) WhisperMenu(vm, server, state) { whisperLists = true } if (state.connected && state.whisperControls) WhisperMenu(whisperLists, server, state) { nav.page = ServerPage.WhisperLists }
IconButton(onClick = find::show) { PackIcon("FIND", "Find") } IconButton(onClick = find::show) { PackIcon("FIND", "Find") }
IconButton(onClick = onSettings) { PackIcon("SETTINGS", "Settings") } IconButton(onClick = onSettings) { PackIcon("SETTINGS", "Settings") }
}, },
@@ -293,394 +161,89 @@ fun ServerScreen(
}, },
bottomBar = { bottomBar = {
Column { Column {
val ptt = rememberPttTarget(vm) val ptt = rememberPttTarget(sessions)
WhisperBanner(state) { server.setWhisper(null) } WhisperBanner(state) { server.setWhisper(null) }
VoiceBar(state, ptt.owner != null, ptt.talking, vm, server, onEnableMicrophone, showChat, chats.anyUnread) { VoiceBar(state, ptt.owner != null, ptt.talking, sessions, server, onEnableMicrophone, nav.showChat, chats.anyUnread) {
showChat = !showChat nav.showChat = !nav.showChat
} }
} }
}, },
snackbarHost = { SnackbarHost(snackbar) }, snackbarHost = { SnackbarHost(snackbar) },
) { padding -> ) { padding ->
Column(Modifier.padding(padding).consumeWindowInsets(padding).imePadding()) { SwipeHost(
if (!showChat) { pageSwipe, nav.showChat,
moving?.let { id -> neighbour = { chat, dir -> if (chatBesideTree && (dir > 0) != chat) !chat else null },
val client = tree.client(id) onSwipe = { nav.showChat = it },
if (client == null) { modifier = Modifier.padding(padding).consumeWindowInsets(padding).imePadding(),
LaunchedEffect(id) { moving = null } ) { chat ->
} else { if (!chat) Column(Modifier.fillMaxSize()) {
MovePrompt(client.name) { moving = null } PickingBar(picking, server, tree, state.channelId) { nav.overlay = Overlay.Kick(it) }
}
}
ChannelTree( ChannelTree(
serverName = state.title, serverName = state.title,
tree = shownTree, tree = treeView.tree,
collapsed = if (treeFiltering) filterCollapsed else collapsed, collapsed = treeView.collapsed,
currentChannel = state.channelId, currentChannel = state.channelId,
onToggle = { onToggle = { treeView.toggle(it.id) },
if (!treeFiltering) server.toggleCollapsed(it.id)
else if (it.id in filterCollapsed) filterCollapsed -= it.id
else filterCollapsed += it.id
},
onChannel = { channel -> onChannel = { channel ->
val client = moving val clients = picking.moving
when { when {
channel.spacer != null -> {} channel.spacer != null -> {}
client != null -> { server.moveClient(client, channel.id); moving = null } clients != null -> picking.moveTo(channel.id, clients)
else -> channelSheet = channel.id else -> nav.overlay = Overlay.Channel(channel.id)
} }
}, },
onChannelDoubleTap = { channel -> onChannelDoubleTap = { channel ->
val client = moving val clients = picking.moving
when { when {
client != null -> { server.moveClient(client, channel.id); moving = null } clients != null -> picking.moveTo(channel.id, clients)
channel.id == state.channelId -> {} channel.id == state.channelId -> {}
else -> join(channel) else -> nav.join(server, channel)
} }
}, },
onClient = { clientSheet = it.id; clientSheetFromTree = true }, onClient = {
onServer = { serverSheet = true }, if (picking.selection.isEmpty()) nav.overlay = Overlay.Client(it.id, fromTree = true)
modifier = Modifier.weight(1f), else picking.toggle(it.id)
reveal = reveal,
onRevealed = { reveal = null },
found = remember(treeHits) { treeHits.mapTo(HashSet()) { TreeRef(treeFind.channels, it) } },
foundCurrent = treeAt?.takeIf { it in treeHits }?.let { TreeRef(treeFind.channels, it) },
listState = treeList,
onShowSelf = {
val path = tree.pathTo(state.selfClientId).orEmpty()
if (treeFiltering) filterCollapsed = filterCollapsed - path.toSet() else server.expand(path)
reveal = TreeRef(false, state.selfClientId)
}, },
onServer = { nav.overlay = Overlay.Server },
modifier = Modifier.weight(1f).swipeSource(when (treeSwipe) {
TreeSwipe.CHAT -> pageSwipe
TreeSwipe.SERVERS -> serverSwipe
TreeSwipe.OFF -> null
}),
reveal = treeView.reveal,
onRevealed = { treeView.reveal = null },
found = treeView.found,
foundCurrent = treeView.current,
listState = treeList,
selected = picking.selection,
onClientLongPress = if (picking.canPick) ({ picking.pick(it.id) }) else null,
onShowSelf = { treeView.show(TreeRef(false, state.selfClientId)) },
) )
} else { } else {
ChatPane( ChatPane(
chats = chats, chats = chats,
selected = conversation, selected = conversation,
canSend = state.connected, canSend = state.connected,
onSelect = { chatKey = it }, onSelect = { nav.chatKey = it },
onClose = { key -> onClose = { key ->
if (chatKey == key) chatKey = ChatKey.Channel if (nav.chatKey == key) nav.chatKey = ChatKey.CHANNEL
server.closePrivateChat(key) server.closePrivateChat(key)
}, },
onSend = { server.send(conversation.key, it) }, onSend = { server.send(conversation.key, it) },
onAttach = attachments.share, onAttach = attachments.share,
onLink = onLink, onLink = onLink,
modifier = Modifier.weight(1f), modifier = Modifier.fillMaxSize(),
lines = chatLines, lines = chatSearch.lines,
find = chatQuery, find = chatSearch.query,
current = chatAt, current = chatSearch.at,
reveal = chatReveal, reveal = chatSearch.reveal,
onRevealed = { chatReveal = null }, onRevealed = { chatSearch.reveal = null },
swipeTabs = chatTabSwipe,
linesModifier = Modifier.swipeSource(if (chatBesideTree) pageSwipe else null),
) )
} }
} }
} }
// A sheet goes with its client or channel when that leaves the tree. ServerOverlay(nav, whisperLists, server, state, tree, treeView, picking, snackbar, onLink, onEditContact, onEditBookmark)
clientSheet?.let { id ->
LaunchedEffect(id) { server.requestClientDetails(id) }
tree.client(id)?.let { client ->
ClientSheet(
client = client,
details = remember(id, tree, infoUpdates) { server.clientDetails(id) },
onLink = onLink,
away = state.away,
initialVolume = remember(id) { server.clientVolume(id) },
onDismiss = { clientSheet = null },
onMessage = {
clientSheet = null
chatKey = server.openPrivateChat(id)
showChat = true
},
onPoke = { server.poke(id, it); clientSheet = null },
onVolume = { server.setClientVolume(id, it) },
onAway = { server.setAway(it); clientSheet = null },
onAddContact = { server.addContact(id, it) },
onEditContact = { clientSheet = null; onEditContact(client.uniqueId) },
onConnectionInfo = { clientSheet = null; connectionInfo = id },
onWhisper = { clientSheet = null; server.whisperToClient(id) },
onAddToWhisperList = {
clientSheet = null
server.clientRef(id)?.let { ref -> toWhisperList = client.name to { it.clients.add(ref) } }
},
onMove = if (server.canMoveClients) ({ clientSheet = null; moving = id }) else null,
onMoveToOwnChannel = if (server.canMoveClients && tree.channel(state.channelId)?.clients?.none { it.id == id } == true) {
{ server.moveClient(id, state.channelId); clientSheet = null }
} else null,
onFindInTree = if (clientSheetFromTree) null else ({
clientSheet = null
tree.pathTo(id)?.let { server.expand(it) }
showChat = false
reveal = TreeRef(false, id)
}),
moderation = { ClientModeration(server, client) { clientSheet = null } },
)
} }
}
channelSheet?.let { id ->
LaunchedEffect(id) { server.requestChannelDetails(id) }
tree.channel(id)?.let { channel ->
ChannelSheet(
channel = channel,
details = remember(id, tree, infoUpdates) { server.channelDetails(id) },
onLink = onLink,
current = id == state.channelId,
onDismiss = { channelSheet = null },
onJoin = { join(channel); channelSheet = null },
onSubscribe = { server.setSubscribed(id, it); channelSheet = null },
onBookmark = { channelSheet = null; bookmarkHere(id) },
onWhisper = { channelSheet = null; server.whisperToChannel(id) },
onAddToWhisperList = {
channelSheet = null
server.channelRef(id)?.let { ref -> toWhisperList = channel.name to { it.channels.add(ref) } }
},
onFiles = {
channelSheet = null
if (channel.locked) filesLocked = id else files = FilesOf(id, channel.name, "")
},
onCreateSub = if (server.canCreateChannels) ({ channelSheet = null; channelEdit = ChannelEdit(0, id) }) else null,
onEdit = if (server.canEditChannels) ({ channelSheet = null; channelEdit = ChannelEdit(id) }) else null,
onDelete = if (server.canDeleteChannels) ({ channelSheet = null; deletingChannel = id }) else null,
)
}
}
joinLocked?.let { id ->
TextPrompt(
title = "Join ${tree.channel(id)?.name.orEmpty()}",
label = "Channel password",
confirm = "Join",
password = true,
onDismiss = { joinLocked = null },
onConfirm = { joinLocked = null; server.joinChannel(id, it) },
)
}
filesLocked?.let { id ->
TextPrompt(
title = "Files of ${tree.channel(id)?.name.orEmpty()}",
label = "Channel password",
confirm = "Open",
password = true,
onDismiss = { filesLocked = null },
onConfirm = { filesLocked = null; files = FilesOf(id, tree.channel(id)?.name.orEmpty(), it) },
)
}
deletingChannel?.let { id ->
val channel = tree.channel(id)
val scope = rememberCoroutineScope()
AlertDialog(
onDismissRequest = { deletingChannel = null },
title = { Text("Delete ${channel?.name.orEmpty()}?") },
text = if (channel != null && (channel.children.isNotEmpty() || channel.clients.isNotEmpty())) {
{ Text("Its sub-channels go with it, and whoever is in it is moved out.") }
} else null,
confirmButton = {
TextButton(onClick = {
deletingChannel = null
scope.launch { server.deleteChannel(id)?.let { snackbar.showSnackbar("Could not delete the channel: $it") } }
}) { Text("Delete") }
},
dismissButton = { TextButton(onClick = { deletingChannel = null }) { Text("Cancel") } },
)
}
toWhisperList?.let { (name, add) ->
AddToWhisperListDialog(vm, name, onDismiss = { toWhisperList = null }) { index, newName ->
toWhisperList = null
vm.addToWhisperList(index, newName, add)
}
}
if (serverSheet) {
remember(tree, infoUpdates) { server.serverDetails() }?.let {
ServerSheet(it, onLink, onDismiss = { serverSheet = false },
onBookmark = { serverSheet = false; bookmarkHere(state.channelId) },
onBanList = if (server.canViewBanList) ({ serverSheet = false; banList = true }) else null,
onCreateChannel = if (server.canCreateChannels) ({ serverSheet = false; channelEdit = ChannelEdit(0, 0) }) else null)
}
}
}
/** More matches than this nobody steps through one by one. */
private const val MAX_CHAT_MATCHES = 5000
/** The index [delta] on from [at] among [size], wrapping around; from none, the first or the last. */
private fun next(at: Int, delta: Int, size: Int): Int =
if (at < 0) (if (delta > 0) 0 else size - 1) else Math.floorMod(at + delta, size)
/** Says a channel is being picked for [name] to move to, until it is or [onCancel]. */
@Composable
private fun MovePrompt(name: String, onCancel: () -> Unit) {
Surface(color = MaterialTheme.colorScheme.secondaryContainer) {
Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) {
PackIcon("CHANNEL_SWITCH", null)
Text("Move $name to…", Modifier.weight(1f).padding(horizontal = 12.dp), maxLines = 1,
overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodyMedium)
TextButton(onClick = onCancel) { Text("Cancel") }
}
}
}
/**
* Mute, deafen, away and the chat, around the push-to-talk button when that is how the
* microphone is used. Holding the mute button switches between push to talk and voice activation.
*/
@Composable
private fun VoiceBar(
state: SessionState,
/** Whether some server holds the microphone, for push-to-talk to talk on. */
captured: Boolean,
talking: Boolean,
vm: SessionController,
server: ServerController,
onEnableMicrophone: () -> Unit,
showChat: Boolean,
unread: Boolean,
onChat: () -> Unit,
) {
val context = LocalContext.current
val ptt = state.connected && captured && state.inputMode == Settings.InputMode.PUSH_TO_TALK
val mic = @Composable {
BarButton(
onClick = { server.setMicMuted(!state.micMuted) },
onLongClick = {
val mode = vm.toggleInputMode()
val text = if (mode == Settings.InputMode.PUSH_TO_TALK) "Switched to push-to-talk mode."
else "Switched to voice activation mode."
Toast.makeText(context, text, Toast.LENGTH_SHORT).show()
},
enabled = state.connected,
) {
if (state.micMuted) PackIcon("INPUT_MUTED", "Unmute microphone")
else PackIcon("CAPTURE", "Mute microphone")
}
}
val deafen = @Composable {
IconToggleButton(state.deafened, { server.setDeafened(it) }, enabled = state.connected) {
if (state.deafened) PackIcon("OUTPUT_MUTED", "Undeafen")
else PackIcon("PLAYBACK", "Deafen")
}
}
// Another server holds the microphone.
val activate = @Composable {
if (state.connected && state.micPermission && !state.micActive) {
IconButton(onClick = onEnableMicrophone) { PackIcon("ACTIVATE_MICROPHONE", "Speak on this server") }
}
}
val middle = @Composable {
when {
ptt -> PushToTalk(talking, vm::setPushToTalk, Modifier.fillMaxWidth().height(48.dp))
!state.micPermission -> FilledTonalButton(onClick = onEnableMicrophone) {
PackIcon("CAPTURE", null)
Text("Use microphone", Modifier.padding(start = 8.dp), maxLines = 1)
}
}
}
val away = @Composable {
IconToggleButton(state.away, { server.setAway(it) }, enabled = state.connected) {
PackIcon("AWAY", if (state.away) "Back" else "Away", Modifier.alpha(if (state.away) 1f else 0.5f))
}
}
val chat = @Composable {
IconToggleButton(showChat, { onChat() }) {
BadgedBox(badge = { if (unread && !showChat) Badge() }) {
PackIcon(listOf("MESSAGES", "CHANNEL_CHAT"), if (showChat) "Channels" else "Chat",
Modifier.alpha(if (showChat) 1f else 0.7f))
}
}
}
Surface(tonalElevation = 3.dp) {
// The same places whatever shows: sides of three buttons each keep the talk button centred.
Row(Modifier.fillMaxWidth().navigationBarsPadding().padding(horizontal = 8.dp, vertical = 4.dp),
horizontalArrangement = Arrangement.spacedBy(4.dp),
verticalAlignment = Alignment.CenterVertically) {
Row(Modifier.width(SIDE), verticalAlignment = Alignment.CenterVertically) {
Slot { mic() }; Slot { deafen() }; Slot { activate() }
}
Box(Modifier.weight(1f).height(48.dp), contentAlignment = Alignment.Center) { middle() }
Row(Modifier.width(SIDE), horizontalArrangement = Arrangement.End, verticalAlignment = Alignment.CenterVertically) {
Slot { away() }; Slot { chat() }
}
}
}
}
private val SLOT = 48.dp
private val SIDE = SLOT * 3
/** One button's place in the bar, kept whether or not the button shows. */
@Composable
private fun Slot(content: @Composable () -> Unit) {
Box(Modifier.size(SLOT), contentAlignment = Alignment.Center) { content() }
}
/** An icon button that also answers a long press. */
@Composable
private fun BarButton(onClick: () -> Unit, onLongClick: () -> Unit, enabled: Boolean, content: @Composable () -> Unit) {
Box(
Modifier
.minimumInteractiveComponentSize()
.size(40.dp)
.clip(CircleShape)
.combinedClickable(enabled = enabled, role = Role.Button, onLongClick = onLongClick, onClick = onClick)
.alpha(if (enabled) 1f else 0.38f),
contentAlignment = Alignment.Center,
) { content() }
}
/** The server's own icon, else the pack's server icon. */
@Composable
private fun ServerLogo(server: ServerController, modifier: Modifier = Modifier) {
val tree by server.tree.collectAsStateWithLifecycle()
val version by server.images.version.collectAsStateWithLifecycle()
val icon = remember(tree.serverIconId, version) { server.images.icon(tree.serverIconId) }
if (icon != null) Image(icon, null, modifier.size(24.dp))
else PackIcon("SERVER_GREEN", null, modifier)
}
/** The server on screen, opening onto the others and connecting to another. */
@Composable
private fun ServerSwitcher(vm: SessionController, server: ServerController, state: SessionState, onConnectOther: () -> Unit) {
val servers by vm.servers.collectAsStateWithLifecycle()
var open by remember { mutableStateOf(false) }
Box(Modifier.fillMaxWidth()) {
Row(Modifier.fillMaxWidth().heightIn(min = 48.dp).clickable { open = true },
verticalAlignment = Alignment.CenterVertically) {
ServerLogo(server, Modifier.padding(end = 12.dp))
Column(Modifier.weight(1f)) {
Text(state.title, maxLines = 1, overflow = TextOverflow.Ellipsis)
if (!state.connected) {
Text(state.status, style = MaterialTheme.typography.bodySmall, maxLines = 1,
overflow = TextOverflow.Ellipsis)
}
}
Icon(Icons.Filled.ArrowDropDown, "Servers")
}
DropdownMenu(open, onDismissRequest = { open = false }) {
for (other in servers) {
key(other.id) {
val otherState by other.state.collectAsStateWithLifecycle()
DropdownMenuItem(
text = { Text(otherState.title, maxLines = 1, overflow = TextOverflow.Ellipsis) },
onClick = { open = false; vm.select(other) },
leadingIcon = {
ServerLogo(other, Modifier.alpha(if (otherState.connected) 1f else 0.5f))
},
trailingIcon = if (otherState.micActive) ({ PackIcon("ACTIVATE_MICROPHONE", "Microphone") }) else null,
colors = if (other == server) MenuDefaults.itemColors(textColor = MaterialTheme.colorScheme.primary)
else MenuDefaults.itemColors(),
)
}
}
HorizontalDivider()
DropdownMenuItem(
text = { Text("Connect…") },
onClick = { open = false; onConnectOther() },
leadingIcon = { PackIcon("CONNECT", null) },
)
DropdownMenuItem(
text = { Text("Disconnect from current") },
onClick = { open = false; server.disconnect() },
leadingIcon = { PackIcon("DISCONNECT", null) },
)
}
}
}
@@ -0,0 +1,94 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MenuDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.android.SessionState
/** The server's own icon, else the pack's server icon. */
@Composable
private fun ServerLogo(server: ServerController, modifier: Modifier = Modifier) {
val tree by server.tree.collectAsStateWithLifecycle()
val version by server.images.version.collectAsStateWithLifecycle()
val icon = remember(tree.serverIconId, version) { server.images.icon(tree.serverIconId) }
if (icon != null) Image(icon, null, modifier.size(24.dp))
else PackIcon("SERVER_GREEN", null, modifier)
}
/** The server on screen, opening onto the others and connecting to another. */
@Composable
internal fun ServerSwitcher(sessions: SessionController, server: ServerController, state: SessionState, onConnectOther: () -> Unit) {
val servers by sessions.servers.collectAsStateWithLifecycle()
var open by remember { mutableStateOf(false) }
Box(Modifier.fillMaxWidth()) {
Row(Modifier.fillMaxWidth().heightIn(min = 48.dp).clickable { open = true },
verticalAlignment = Alignment.CenterVertically) {
ServerLogo(server, Modifier.padding(end = 12.dp))
Column(Modifier.weight(1f)) {
Text(state.title, maxLines = 1, overflow = TextOverflow.Ellipsis)
if (!state.connected) {
Text(state.status, style = MaterialTheme.typography.bodySmall, maxLines = 1,
overflow = TextOverflow.Ellipsis)
}
}
Icon(Icons.Filled.ArrowDropDown, "Servers")
}
DropdownMenu(open, onDismissRequest = { open = false }) {
for (other in servers) {
key(other.id) {
val otherState by other.state.collectAsStateWithLifecycle()
DropdownMenuItem(
text = { Text(otherState.title, maxLines = 1, overflow = TextOverflow.Ellipsis) },
onClick = { open = false; sessions.select(other) },
leadingIcon = {
ServerLogo(other, Modifier.alpha(if (otherState.connected) 1f else 0.5f))
},
trailingIcon = if (otherState.micActive) ({ PackIcon("ACTIVATE_MICROPHONE", "Microphone") }) else null,
colors = if (other == server) MenuDefaults.itemColors(textColor = MaterialTheme.colorScheme.primary)
else MenuDefaults.itemColors(),
)
}
}
HorizontalDivider()
DropdownMenuItem(
text = { Text("Connect…") },
onClick = { open = false; onConnectOther() },
leadingIcon = { PackIcon("CONNECT", null) },
)
DropdownMenuItem(
text = { Text("Disconnect from current") },
onClick = { open = false; server.disconnect() },
leadingIcon = { PackIcon("DISCONNECT", null) },
)
}
}
}
@@ -16,8 +16,12 @@ import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier import androidx.compose.ui.Modifier
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.AppParts
import eu.lixko.ts3j.client.android.IconTheme import eu.lixko.ts3j.client.android.IconTheme
import eu.lixko.ts3j.client.android.SessionController import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.android.SwipePrefs
import eu.lixko.ts3j.client.android.TreeSwipe
import eu.lixko.ts3j.client.config.Settings
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
@@ -29,15 +33,15 @@ private enum class SettingsPage { SOUND, NETWORK, GIANT_PTT, DESIGN, IDENTITIES,
* as there is no dialog to confirm. * as there is no dialog to confirm.
*/ */
@Composable @Composable
fun SettingsScreen(vm: SessionController, onContacts: () -> Unit, onBack: () -> Unit) { fun SettingsScreen(parts: AppParts, onContacts: () -> Unit, onBack: () -> Unit) {
var page by rememberSaveable { mutableStateOf<SettingsPage?>(null) } var page by rememberSaveable { mutableStateOf<SettingsPage?>(null) }
when (page) { when (page) {
SettingsPage.SOUND -> return SoundSettingsScreen(vm, onBack = { page = null }) SettingsPage.SOUND -> return SoundSettingsScreen(parts.settings, parts.sessions, parts.audio, onBack = { page = null })
SettingsPage.NETWORK -> return NetworkSettingsScreen(vm, onBack = { page = null }) SettingsPage.NETWORK -> return NetworkSettingsScreen(parts.settings, parts.sessions, onBack = { page = null })
SettingsPage.GIANT_PTT -> return GiantPttScreen(vm, onBack = { page = null }) SettingsPage.GIANT_PTT -> return GiantPttScreen(parts.sessions, onBack = { page = null })
SettingsPage.DESIGN -> return DesignScreen(vm, onBack = { page = null }) SettingsPage.DESIGN -> return DesignScreen(parts.settings, parts.icons, parts.swipe, parts.sessions, onBack = { page = null })
SettingsPage.IDENTITIES -> return IdentitiesScreen(vm.identities, onBack = { page = null }) SettingsPage.IDENTITIES -> return IdentitiesScreen(parts.identities, onBack = { page = null })
SettingsPage.MY_TEAMSPEAK -> return MyTeamSpeakScreen(vm, onBack = { page = null }) SettingsPage.MY_TEAMSPEAK -> return MyTeamSpeakScreen(parts.myTeamSpeak, onBack = { page = null })
null -> {} null -> {}
} }
@@ -59,48 +63,59 @@ fun SettingsScreen(vm: SessionController, onContacts: () -> Unit, onBack: () ->
LinkRow("Identities", "Create, import, export, security level", LinkRow("Identities", "Create, import, export, security level",
"IDENTITY_MANAGER") { page = SettingsPage.IDENTITIES } "IDENTITY_MANAGER") { page = SettingsPage.IDENTITIES }
LinkRow("myTeamSpeak", LinkRow("myTeamSpeak",
if (vm.myTeamSpeak.isSignedIn) "Signed in as ${vm.myTeamSpeak.username()}" if (parts.myTeamSpeak.login.isSignedIn) "Signed in as ${parts.myTeamSpeak.login.username()}"
else "Sign in to bring over your synchronised bookmarks and identities", else "Sign in to bring over your synchronised bookmarks, identities and contacts",
"MYTS_ACCOUNT") { page = SettingsPage.MY_TEAMSPEAK } "MYTS_ACCOUNT") { page = SettingsPage.MY_TEAMSPEAK }
} }
} }
} }
@Composable @Composable
private fun DesignScreen(vm: SessionController, onBack: () -> Unit) { private fun DesignScreen(settings: Settings, icons: IconTheme, swipe: SwipePrefs, sessions: SessionController, onBack: () -> Unit) {
SubScreen("Design", onBack) { padding -> SubScreen("Design", onBack) { padding ->
Column(Modifier.padding(padding).verticalScroll(rememberScrollState())) { Column(Modifier.padding(padding).verticalScroll(rememberScrollState())) {
IconPackPicker(vm.icons) IconPackPicker(icons)
var pictures by remember { mutableStateOf(vm.settings.descriptionPictures) } var pictures by remember { mutableStateOf(settings.descriptionPictures.get()) }
Toggle("Show pictures in descriptions", pictures) { Toggle("Show pictures in descriptions", pictures) {
pictures = it pictures = it
vm.setDescriptionPictures(it) settings.descriptionPictures.set(it)
settings.save()
} }
Section("Channel tree") Section("Channel tree")
var flags by remember { mutableStateOf(vm.settings.countryFlags) } var flags by remember { mutableStateOf(settings.countryFlags.get()) }
Toggle("Show country flags in the channel tree", flags) { Toggle("Show country flags in the channel tree", flags) {
flags = it flags = it
vm.setCountryFlags(it) settings.countryFlags.set(it)
settings.save()
} }
val colors = vm.settings.clientRowColors val colors = settings.clientRowColors
var any by remember { mutableIntStateOf(colors.any) } var any by remember { mutableIntStateOf(colors.any) }
var talking by remember { mutableIntStateOf(colors.talking) } var talking by remember { mutableIntStateOf(colors.talking) }
var mutedAway by remember { mutableIntStateOf(colors.mutedAway) } var mutedAway by remember { mutableIntStateOf(colors.mutedAway) }
RowColorPicker("Client background", any) { RowColorPicker("Client background", any) {
any = it any = it
colors.any = it colors.any = it
vm.clientRowColorsChanged() sessions.clientRowColorsChanged()
} }
RowColorPicker("While talking", talking) { RowColorPicker("While talking", talking) {
talking = it talking = it
colors.talking = it colors.talking = it
vm.clientRowColorsChanged() sessions.clientRowColorsChanged()
} }
RowColorPicker("Muted / away", mutedAway) { RowColorPicker("Muted / away", mutedAway) {
mutedAway = it mutedAway = it
colors.mutedAway = it colors.mutedAway = it
vm.clientRowColorsChanged() sessions.clientRowColorsChanged()
} }
val treeSwipe by swipe.tree.collectAsStateWithLifecycle()
Picker("Swipe sideways", listOf(
TreeSwipe.OFF to "Off",
TreeSwipe.CHAT to "Channel tree and chat",
TreeSwipe.SERVERS to "Connected servers",
), treeSwipe, swipe::setTree)
Section("Chat")
val chatTabSwipe by swipe.chatTabs.collectAsStateWithLifecycle()
Toggle("Swipe between chat tabs", chatTabSwipe, swipe::setChatTabs)
} }
} }
} }
@@ -124,4 +139,3 @@ private fun IconPackPicker(theme: IconTheme) {
} }
failed?.let { Hint(it) } failed?.let { Hint(it) }
} }
@@ -1,6 +1,19 @@
package eu.lixko.ts3j.client.android.ui package eu.lixko.ts3j.client.android.ui
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material3.Icon
import androidx.compose.foundation.relocation.BringIntoViewRequester
import androidx.compose.foundation.relocation.bringIntoViewRequester
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.layout.onSizeChanged
import kotlinx.coroutines.launch
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.fillMaxWidth
@@ -51,22 +64,32 @@ fun ClientSheet(
onPoke: (String) -> Unit, onPoke: (String) -> Unit,
onVolume: (Double) -> Unit, onVolume: (Double) -> Unit,
onAway: (Boolean) -> Unit, onAway: (Boolean) -> Unit,
/** Asks for talk power with a reason, or withdraws the request with null; null when we may not ask. */
onTalkRequest: ((String?) -> Unit)?,
onAddContact: (ContactType) -> Unit, onAddContact: (ContactType) -> Unit,
onEditContact: () -> Unit, onEditContact: () -> Unit,
onConnectionInfo: () -> Unit, onConnectionInfo: () -> Unit,
onWhisper: () -> Unit, /** Both null when whisper controls are hidden. */
onAddToWhisperList: () -> Unit, onWhisper: (() -> Unit)?,
onAddToWhisperList: (() -> Unit)?,
/** Null when the client cannot be moved. */ /** Null when the client cannot be moved. */
onMove: (() -> Unit)?, onMove: (() -> Unit)?,
/** Null when the client cannot be moved, or is in our channel already. */ /** Null when the client cannot be moved, or is in our channel already. */
onMoveToOwnChannel: (() -> Unit)?, onMoveToOwnChannel: (() -> Unit)?,
/** Null when the sheet was opened from the tree. */ /** Null when the sheet was opened from the tree. */
onFindInTree: (() -> Unit)?, onFindInTree: (() -> Unit)?,
/** Kicks, bans and groups, as far as we may use them. */ /** Kicks, bans and groups, as far as we may use them; null when there are none. */
moderation: @Composable () -> Unit = {}, moderation: (@Composable () -> Unit)? = null,
) { ) {
var poking by remember { mutableStateOf(false) } var poking by remember { mutableStateOf(false) }
ModalBottomSheet(onDismissRequest = onDismiss) { var requesting by remember { mutableStateOf(false) }
val sheetState = rememberModalBottomSheetState()
val scope = rememberCoroutineScope()
// A half-open sheet would fold the admin actions out below the screen's edge.
val adminActions = @Composable { content: @Composable ColumnScope.() -> Unit ->
ExpandableAction("PERMISSIONS_CLIENTS", "Admin actions…", onExpand = { scope.launch { sheetState.expand() } }, content)
}
ModalBottomSheet(onDismissRequest = onDismiss, sheetState = sheetState) {
Column(Modifier.verticalScroll(rememberScrollState()).navigationBarsPadding().padding(bottom = 16.dp)) { Column(Modifier.verticalScroll(rememberScrollState()).navigationBarsPadding().padding(bottom = 16.dp)) {
Row(Modifier.padding(horizontal = 24.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically, Row(Modifier.padding(horizontal = 24.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(12.dp)) { horizontalArrangement = Arrangement.spacedBy(12.dp)) {
@@ -90,18 +113,25 @@ fun ClientSheet(
} }
details?.let { DetailsSection(it, onLink, Modifier.padding(bottom = 8.dp)) } details?.let { DetailsSection(it, onLink, Modifier.padding(bottom = 8.dp)) }
onFindInTree?.let { Action("CHANNEL_SWITCH", "Find client in channel tree", onClick = it) } onFindInTree?.let { Action("CHANNEL_SWITCH", "Find client in channel tree", onClick = it) }
Action("INFO", "Connection info", onClick = onConnectionInfo)
if (client.self) { if (client.self) {
Action("AWAY", if (away) "Back" else "Away") { onAway(!away) } Action("AWAY", if (away) "Back" else "Away") { onAway(!away) }
moderation() onTalkRequest?.let { request ->
if (client.talkRequest) Action("TALK_POWER_CANCEL_REQUEST", "Cancel talk power request") { request(null) }
else Action("TALK_POWER_REQUEST", "Request talk power") { requesting = true }
}
moderation?.let { adminActions { it() } }
} else { } else {
Action("PLAYER_CHAT", "Send message", onClick = onMessage) Action("PLAYER_CHAT", "Send message", onClick = onMessage)
Action("POKE", "Poke") { poking = true } Action("POKE", "Poke") { poking = true }
Action("PLAYER_WHISPER", "Whisper", onClick = onWhisper) onWhisper?.let { Action("PLAYER_WHISPER", "Whisper", onClick = it) }
Action("ON_WHISPERLIST", "Add to whisper list…", onClick = onAddToWhisperList) // "Add to whisper list…" (onAddToWhisperList) is left out for now.
onMove?.let { Action("CHANNEL_SWITCH", "Move to channel…", onClick = it) }
onMoveToOwnChannel?.let { Action("MOVE_CLIENT_TO_OWN_CHANNEL", "Move to own channel", onClick = it) } onMoveToOwnChannel?.let { Action("MOVE_CLIENT_TO_OWN_CHANNEL", "Move to own channel", onClick = it) }
moderation() if (onMove != null || moderation != null) {
adminActions {
onMove?.let { Action("CHANNEL_SWITCH", "Move to channel…", onClick = it) }
moderation?.invoke()
}
}
if (client.contactType == null) { if (client.contactType == null) {
Row { Row {
Action("ADD_FRIEND", "Add as friend", Modifier.weight(1f)) { onAddContact(ContactType.FRIEND) } Action("ADD_FRIEND", "Add as friend", Modifier.weight(1f)) { onAddContact(ContactType.FRIEND) }
@@ -110,6 +140,9 @@ fun ClientSheet(
} else { } else {
Action("EDIT_FRIEND_FOE_STATUS", "Edit contact", onClick = onEditContact) Action("EDIT_FRIEND_FOE_STATUS", "Edit contact", onClick = onEditContact)
} }
}
Action("INFO", "Connection info", onClick = onConnectionInfo)
if (!client.self) {
var volume by remember { mutableFloatStateOf(initialVolume.toFloat()) } var volume by remember { mutableFloatStateOf(initialVolume.toFloat()) }
Text("Volume: ${if (volume > 0) "+" else ""}${volume.roundToInt()} dB", Text("Volume: ${if (volume > 0) "+" else ""}${volume.roundToInt()} dB",
Modifier.padding(start = 24.dp, top = 8.dp), style = MaterialTheme.typography.bodyMedium) Modifier.padding(start = 24.dp, top = 8.dp), style = MaterialTheme.typography.bodyMedium)
@@ -131,6 +164,15 @@ fun ClientSheet(
onConfirm = { poking = false; onPoke(it) }, onConfirm = { poking = false; onPoke(it) },
) )
} }
if (requesting) {
TextPrompt(
title = "Request talk power",
label = "Reason",
confirm = "Request",
onDismiss = { requesting = false },
onConfirm = { requesting = false; onTalkRequest?.invoke(it.trim()) },
)
}
} }
/** What can be done with a channel: join it, whether to hear who is in it, whisper to it, its files, and editing it. */ /** What can be done with a channel: join it, whether to hear who is in it, whisper to it, its files, and editing it. */
@@ -144,11 +186,11 @@ fun ChannelSheet(
onDismiss: () -> Unit, onDismiss: () -> Unit,
onJoin: () -> Unit, onJoin: () -> Unit,
onSubscribe: (Boolean) -> Unit, onSubscribe: (Boolean) -> Unit,
onBookmark: () -> Unit, /** Both null when whisper controls are hidden. */
onWhisper: () -> Unit, onWhisper: (() -> Unit)?,
onAddToWhisperList: () -> Unit, onAddToWhisperList: (() -> Unit)?,
onFiles: () -> Unit,
/** Each null when we may not. */ /** Each null when we may not. */
onFiles: (() -> Unit)?,
onCreateSub: (() -> Unit)?, onCreateSub: (() -> Unit)?,
onEdit: (() -> Unit)?, onEdit: (() -> Unit)?,
onDelete: (() -> Unit)?, onDelete: (() -> Unit)?,
@@ -166,10 +208,9 @@ fun ChannelSheet(
} else { } else {
Action("SUBSCRIBE_TO_CHANNEL", "Subscribe") { onSubscribe(true) } Action("SUBSCRIBE_TO_CHANNEL", "Subscribe") { onSubscribe(true) }
} }
Action("WHISPER", "Whisper", onClick = onWhisper) onWhisper?.let { Action("WHISPER", "Whisper", onClick = it) }
Action("ON_WHISPERLIST", "Add to whisper list…", onClick = onAddToWhisperList) onAddToWhisperList?.let { Action("ON_WHISPERLIST", "Add to whisper list…", onClick = it) }
Action("FILETRANSFER", "Browse files", onClick = onFiles) onFiles?.let { Action("FILETRANSFER", "Browse files", onClick = it) }
Action("BOOKMARK_ADD", "Add to bookmarks", onClick = onBookmark)
onCreateSub?.let { Action("CHANNEL_CREATE_SUB", "Create sub-channel", onClick = it) } onCreateSub?.let { Action("CHANNEL_CREATE_SUB", "Create sub-channel", onClick = it) }
onEdit?.let { Action("CHANNEL_EDIT", "Edit channel", onClick = it) } onEdit?.let { Action("CHANNEL_EDIT", "Edit channel", onClick = it) }
onDelete?.let { Action("CHANNEL_DELETE", "Delete channel", onClick = it) } onDelete?.let { Action("CHANNEL_DELETE", "Delete channel", onClick = it) }
@@ -213,6 +254,36 @@ internal fun Action(iconKey: String, label: String, modifier: Modifier = Modifie
) )
} }
/** A row that, once tapped, gives its place to the [content] it stands for, scrolled into view. */
@Composable
internal fun ExpandableAction(
iconKey: String,
label: String,
onExpand: () -> Unit = {},
content: @Composable ColumnScope.() -> Unit,
) {
var expanded by remember { mutableStateOf(false) }
val scope = rememberCoroutineScope()
val inView = remember { BringIntoViewRequester() }
if (!expanded) {
ListItem(
headlineContent = { Text(label) },
leadingContent = { PackIcon(iconKey, null) },
trailingContent = { Icon(Icons.Filled.KeyboardArrowDown, null) },
colors = ListItemDefaults.colors(containerColor = Color.Transparent),
modifier = Modifier.fillMaxWidth().clickable { expanded = true; onExpand() }.padding(horizontal = 8.dp),
)
}
AnimatedVisibility(expanded, enter = expandVertically() + fadeIn()) {
Column(
Modifier.bringIntoViewRequester(inView)
// Follows the items as they unfold.
.onSizeChanged { scope.launch { inView.bringIntoView() } },
content = content,
)
}
}
/** Asks for one line of text. */ /** Asks for one line of text. */
@Composable @Composable
fun TextPrompt( fun TextPrompt(
@@ -30,11 +30,13 @@ import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.LifecycleStartEffect import androidx.lifecycle.compose.LifecycleStartEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.AudioSetup
import eu.lixko.ts3j.client.android.MicLevel import eu.lixko.ts3j.client.android.MicLevel
import eu.lixko.ts3j.client.android.SessionController import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.android.audio.AudioRoute import eu.lixko.ts3j.client.android.audio.AudioRoute
import eu.lixko.ts3j.client.audio.AudioDevice import eu.lixko.ts3j.client.audio.AudioDevice
import eu.lixko.ts3j.client.audio.InputLevel import eu.lixko.ts3j.client.audio.InputLevel
import eu.lixko.ts3j.client.config.Setting
import eu.lixko.ts3j.client.config.Settings import eu.lixko.ts3j.client.config.Settings
import kotlin.math.roundToInt import kotlin.math.roundToInt
@@ -42,28 +44,27 @@ private val DENOISE_LEVELS = listOf("Off", "6 dB", "12 dB", "18 dB", "21 dB")
/** Audio devices, transmission, voice activation, processing and playback. */ /** Audio devices, transmission, voice activation, processing and playback. */
@Composable @Composable
fun SoundSettingsScreen(vm: SessionController, onBack: () -> Unit) { fun SoundSettingsScreen(settings: Settings, sessions: SessionController, audio: AudioSetup, onBack: () -> Unit) {
val settings = vm.settings fun <T> change(setting: Setting<T>, value: T) {
fun change(edit: Settings.() -> Unit) { setting.set(value)
settings.edit() sessions.applySettings()
vm.applySettings()
} }
var inputMode by remember { mutableStateOf(settings.inputMode) } var inputMode by remember { mutableStateOf(settings.inputMode.get()) }
var vadMode by remember { mutableStateOf(settings.vadMode) } var vadMode by remember { mutableStateOf(settings.vadMode.get()) }
var agc by remember { mutableStateOf(settings.agc) } var agc by remember { mutableStateOf(settings.agc.get()) }
var mutedTalkWarning by remember { mutableStateOf(settings.mutedTalkWarning) } var mutedTalkWarning by remember { mutableStateOf(settings.mutedTalkWarning.get()) }
var threshold by remember { mutableFloatStateOf(settings.vadThresholdDb.toFloat()) } var threshold by remember { mutableFloatStateOf(settings.vadThresholdDb.get().toFloat()) }
var inputDevice by remember { mutableStateOf(settings.inputDevice) } var inputDevice by remember { mutableStateOf(settings.inputDevice.get()) }
var outputDevice by remember { mutableStateOf(settings.outputDevice) } var outputDevice by remember { mutableStateOf(settings.outputDevice.get()) }
val inputs by vm.inputDevices.collectAsStateWithLifecycle() val inputs by audio.inputDevices.collectAsStateWithLifecycle()
val outputs by vm.outputDevices.collectAsStateWithLifecycle() val outputs by audio.outputDevices.collectAsStateWithLifecycle()
val route by vm.route.collectAsStateWithLifecycle() val route by audio.route.collectAsStateWithLifecycle()
val level by vm.micLevel.collectAsStateWithLifecycle() val level by sessions.micLevel.collectAsStateWithLifecycle()
val packs by vm.soundPacks.collectAsStateWithLifecycle() val packs by audio.soundPacks.collectAsStateWithLifecycle()
var pack by remember { mutableStateOf(vm.soundPack?.id()) } var pack by remember { mutableStateOf(audio.soundPack?.id()) }
LifecycleStartEffect(Unit) { LifecycleStartEffect(Unit) {
vm.watchLevel(true) sessions.watchLevel(true)
onStopOrDispose { vm.watchLevel(false) } onStopOrDispose { sessions.watchLevel(false) }
} }
SubScreen("Sound Settings", onBack) { padding -> SubScreen("Sound Settings", onBack) { padding ->
@@ -71,38 +72,38 @@ fun SoundSettingsScreen(vm: SessionController, onBack: () -> Unit) {
Section("Devices") Section("Devices")
DevicePicker("Microphone", inputs, inputDevice) { DevicePicker("Microphone", inputs, inputDevice) {
inputDevice = it inputDevice = it
change { this.inputDevice = it } change(settings.inputDevice, it)
} }
DevicePicker("Speaker", outputs, outputDevice) { DevicePicker("Speaker", outputs, outputDevice) {
outputDevice = it outputDevice = it
change { this.outputDevice = it } change(settings.outputDevice, it)
} }
Picker( Picker(
"Microphone preset", "Microphone preset",
INPUT_PRESETS.map { (preset, label) -> INPUT_PRESETS.map { (preset, label) ->
val unsupported = preset == AudioRoute.InputPreset.UNPROCESSED && !vm.unprocessedSupported val unsupported = preset == AudioRoute.InputPreset.UNPROCESSED && !audio.unprocessedSupported
preset to if (unsupported) "$label (not supported here)" else label preset to if (unsupported) "$label (not supported here)" else label
}, },
route.inputPreset(), route.inputPreset(),
) { vm.setRoute(AudioRoute(it, route.usage())) } ) { audio.setRoute(AudioRoute(it, route.usage())) }
Hint(PRESET_HINTS.getValue(route.inputPreset())) Hint(PRESET_HINTS.getValue(route.inputPreset()))
Text("Play voices", Modifier.padding(start = 16.dp, top = 8.dp)) Text("Play voices", Modifier.padding(start = 16.dp, top = 8.dp))
for ((usage, label) in USAGES) { for ((usage, label) in USAGES) {
Choice(label, route.usage() == usage) { vm.setRoute(AudioRoute(route.inputPreset(), usage)) } Choice(label, route.usage() == usage) { audio.setRoute(AudioRoute(route.inputPreset(), usage)) }
} }
Section("Transmission") Section("Transmission")
for ((mode, label) in INPUT_MODES) { for ((mode, label) in INPUT_MODES) {
Choice(label, inputMode == mode) { Choice(label, inputMode == mode) {
inputMode = mode inputMode = mode
change { this.inputMode = mode } change(settings.inputMode, mode)
} }
} }
if (inputMode == Settings.InputMode.PUSH_TO_TALK) FloatingButtonToggle(vm) if (inputMode == Settings.InputMode.PUSH_TO_TALK) FloatingButtonToggle(audio)
val gated = inputMode == Settings.InputMode.VOICE_ACTIVATION && vadMode != Settings.VadMode.AUTOMATIC val gated = inputMode == Settings.InputMode.VOICE_ACTIVATION && vadMode != Settings.VadMode.AUTOMATIC
LevelMeter(level, threshold.takeIf { gated }) LevelMeter(level, threshold.takeIf { gated })
if (!level.live) { if (!level.live) {
Hint(if (vm.hasMicPermission()) "The microphone is not available right now." else "Allow the microphone to see its level.") Hint(if (sessions.hasMicPermission()) "The microphone is not available right now." else "Allow the microphone to see its level.")
} }
if (inputMode == Settings.InputMode.VOICE_ACTIVATION) { if (inputMode == Settings.InputMode.VOICE_ACTIVATION) {
@@ -110,46 +111,45 @@ fun SoundSettingsScreen(vm: SessionController, onBack: () -> Unit) {
for ((mode, label) in VAD_MODES) { for ((mode, label) in VAD_MODES) {
Choice(label, vadMode == mode) { Choice(label, vadMode == mode) {
vadMode = mode vadMode = mode
change { this.vadMode = mode } change(settings.vadMode, mode)
} }
} }
if (vadMode != Settings.VadMode.AUTOMATIC) { if (vadMode != Settings.VadMode.AUTOMATIC) {
Level("Volume threshold", settings.vadThresholdDb.toFloat(), -50f..50f, { "${it.roundToInt()}" }, Level("Volume threshold", settings.vadThresholdDb.get().toFloat(), -50f..50f, { "${it.roundToInt()}" },
onChange = { threshold = it }) { onChange = { threshold = it }) {
change { vadThresholdDb = it.roundToInt().toDouble() } change(settings.vadThresholdDb, it.roundToInt().toDouble())
} }
} }
if (vadMode != Settings.VadMode.VOLUME_GATE) { if (vadMode != Settings.VadMode.VOLUME_GATE) {
Level("Speech likelihood", settings.speechThreshold.toFloat(), 0f..1f, { "${(it * 100).roundToInt()} %" }) { Level("Speech likelihood", settings.speechThreshold.get().toFloat(), 0f..1f, { "${(it * 100).roundToInt()} %" }) {
change { speechThreshold = it.toDouble() } change(settings.speechThreshold, it.toDouble())
} }
} }
} }
Section("Processing") Section("Processing")
val suppression = if (settings.denoise) settings.denoiserLevel + 1 else 0 val suppression = if (settings.denoise.get()) settings.denoiserLevel.get() + 1 else 0
Level("Noise suppression", suppression.toFloat(), 0f..DENOISE_LEVELS.lastIndex.toFloat(), Level("Noise suppression", suppression.toFloat(), 0f..DENOISE_LEVELS.lastIndex.toFloat(),
{ DENOISE_LEVELS[it.roundToInt()] }, steps = DENOISE_LEVELS.lastIndex - 1) { { DENOISE_LEVELS[it.roundToInt()] }, steps = DENOISE_LEVELS.lastIndex - 1) {
val step = it.roundToInt() val step = it.roundToInt()
change { settings.denoise.set(step > 0)
denoise = step > 0 if (step > 0) settings.denoiserLevel.set(step - 1)
if (step > 0) denoiserLevel = step - 1 sessions.applySettings()
}
} }
Toggle("Automatic gain control", agc) { Toggle("Automatic gain control", agc) {
agc = it agc = it
change { this.agc = it } change(settings.agc, it)
} }
if (agc) { if (agc) {
Level("Boost quiet speech", settings.agcBoostDb.toFloat(), 0f..Settings.MAX_AGC_BOOST_DB.toFloat(), Level("Boost quiet speech", settings.agcBoostDb.get().toFloat(), 0f..Settings.MAX_AGC_BOOST_DB.toFloat(),
{ "+${it.roundToInt()} dB" }, steps = Settings.MAX_AGC_BOOST_DB - 1) { { "+${it.roundToInt()} dB" }, steps = Settings.MAX_AGC_BOOST_DB - 1) {
change { agcBoostDb = it.roundToInt() } change(settings.agcBoostDb, it.roundToInt())
} }
} }
Section("Playback") Section("Playback")
Level("Volume", settings.outputVolume.toFloat(), 0f..2f, { "${(it * 100).roundToInt()} %" }) { Level("Volume", settings.outputVolume.get().toFloat(), 0f..2f, { "${(it * 100).roundToInt()} %" }) {
change { outputVolume = it.toDouble() } change(settings.outputVolume, it.toDouble())
} }
Section("Notification sounds") Section("Notification sounds")
@@ -157,16 +157,16 @@ fun SoundSettingsScreen(vm: SessionController, onBack: () -> Unit) {
Hint("This build of the app came without sound packs.") Hint("This build of the app came without sound packs.")
} else { } else {
Picker("Sound pack", packs.map { it.id() to it.name() }, pack) { id -> Picker("Sound pack", packs.map { it.id() to it.name() }, pack) { id ->
packs.firstOrNull { it.id() == id }?.let(vm::setSoundPack) packs.firstOrNull { it.id() == id }?.let(audio::setSoundPack)
pack = id pack = id
} }
} }
Level("Volume", settings.soundVolume.toFloat(), 0f..1f, { "${(it * 100).roundToInt()} %" }) { Level("Volume", settings.soundVolume.get().toFloat(), 0f..1f, { "${(it * 100).roundToInt()} %" }) {
change { soundVolume = it.toDouble() } change(settings.soundVolume, it.toDouble())
} }
Toggle("Beep when talking while muted", mutedTalkWarning) { Toggle("Beep when talking while muted", mutedTalkWarning) {
mutedTalkWarning = it mutedTalkWarning = it
change { this.mutedTalkWarning = it } change(settings.mutedTalkWarning, it)
} }
} }
} }
@@ -210,14 +210,14 @@ private val VAD_MODES = listOf(
/** The push-to-talk button over other apps, which first needs the user to allow the app to draw there. */ /** The push-to-talk button over other apps, which first needs the user to allow the app to draw there. */
@Composable @Composable
private fun FloatingButtonToggle(vm: SessionController) { private fun FloatingButtonToggle(audio: AudioSetup) {
val context = LocalContext.current val context = LocalContext.current
val enabled by vm.pttOverlay.collectAsStateWithLifecycle() val enabled by audio.pttOverlay.collectAsStateWithLifecycle()
val allow = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { val allow = rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (canDrawOverlays(context)) vm.setPttOverlay(true) if (canDrawOverlays(context)) audio.setPttOverlay(true)
} }
Toggle("Floating button over other apps", enabled && canDrawOverlays(context)) { on -> Toggle("Floating button over other apps", enabled && canDrawOverlays(context)) { on ->
if (!on || canDrawOverlays(context)) vm.setPttOverlay(on) if (!on || canDrawOverlays(context)) audio.setPttOverlay(on)
else allow.launch(Intent(ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:${context.packageName}"))) else allow.launch(Intent(ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:${context.packageName}")))
} }
Hint("Hold it to talk. Double-tap and keep holding to drag it elsewhere.") Hint("Hold it to talk. Double-tap and keep holding to drag it elsewhere.")
@@ -0,0 +1,152 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.animation.core.animate
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.awaitHorizontalTouchSlopOrCancellation
import androidx.compose.foundation.gestures.horizontalDrag
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.PointerId
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.input.pointer.positionChange
import androidx.compose.ui.input.pointer.positionChangeIgnoreConsumed
import androidx.compose.ui.input.pointer.util.VelocityTracker
import androidx.compose.ui.input.pointer.util.addPointerInputChange
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlin.math.abs
import kotlin.math.sign
/** How fast a short swipe must be to turn the page. */
private val FLING_VELOCITY = 600.dp
/** Where a sideways swipe between a [SwipeHost]'s pages is at. */
@Stable
class SwipeState {
/** How far the page on show has moved, in pixels; negative to the left. */
internal var shift by mutableFloatStateOf(0f)
/** Whether a swipe is under way, so the pages either side are on show too. */
internal var active by mutableStateOf(false)
/** The pointer that went down over one of the [swipeSource]s. */
internal var armed: PointerId? = null
}
@Composable
internal fun rememberSwipeState() = remember { SwipeState() }
/** Lets a swipe that starts over this element turn [state]'s pages. */
internal fun Modifier.swipeSource(state: SwipeState?): Modifier =
if (state == null) this else pointerInput(state) {
awaitEachGesture {
// Seen before the host looks at the same press.
state.armed = awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial).id
}
}
/**
* Pages side by side, [current] on show and those either side ([neighbour] gives them, -1 to the left,
* 1 to the right) following the finger. A swipe has to start over a [swipeSource] of [state];
* one that has no page to go to is left to a host further out. [onSwipe] is told of the page swiped to.
* Pages are told apart by equality, so [T] should be a key rather than a snapshot of what it shows.
*/
@Composable
internal fun <T : Any> SwipeHost(
state: SwipeState,
current: T,
neighbour: (T, Int) -> T?,
onSwipe: (T) -> Unit,
modifier: Modifier = Modifier,
page: @Composable (T) -> Unit,
) {
var shown by remember { mutableStateOf(current) }
/** A page swiped to that [current] has not caught up with yet. */
var awaited by remember { mutableStateOf<T?>(null) }
val latest by rememberUpdatedState(current)
val pageNear by rememberUpdatedState(neighbour)
val swiped by rememberUpdatedState(onSwipe)
val scope = rememberCoroutineScope()
var settling by remember { mutableStateOf<Job?>(null) }
LaunchedEffect(current) {
awaited = null
if (!state.active) shown = current
}
Box(modifier.clipToBounds().pointerInput(state) {
awaitEachGesture {
val down = awaitFirstDown(requireUnconsumed = false)
if (state.armed != down.id) return@awaitEachGesture
val start = awaitHorizontalTouchSlopOrCancellation(down.id) { change, over ->
if (pageNear(shown, direction(over)) != null) change.consume()
} ?: return@awaitEachGesture
settling?.cancel()
state.active = true
val width = size.width.toFloat()
val left = pageNear(shown, -1)
val right = pageNear(shown, 1)
val drag = { dx: Float ->
state.shift = (state.shift + dx).coerceIn(if (right != null) -width else 0f, if (left != null) width else 0f)
}
val velocity = VelocityTracker()
velocity.addPointerInputChange(start)
drag(start.positionChangeIgnoreConsumed().x)
val lifted = horizontalDrag(start.id) { change ->
drag(change.positionChange().x)
change.consume()
velocity.addPointerInputChange(change)
}
val fling = if (lifted) velocity.calculateVelocity().x else 0f
val from = state.shift
val dir = when {
abs(fling) > FLING_VELOCITY.toPx() -> direction(fling)
abs(from) > width / 3 -> direction(from)
else -> 0
}
// A fling back against the swipe turns no page.
val target = if (dir != 0 && dir == direction(from)) pageNear(shown, dir) else null
settling = scope.launch {
animate(from, if (target != null) -dir * width else 0f, fling) { value, _ -> state.shift = value }
if (target != null) {
shown = target
awaited = target
swiped(target)
} else if (awaited == null) {
shown = latest
}
state.shift = 0f
state.active = false
}
}
}) {
val at = shown
val pages = if (!state.active) listOf(at to 0)
else listOfNotNull(neighbour(at, -1)?.to(-1), at to 0, neighbour(at, 1)?.to(1))
for ((item, slot) in pages) {
// Keyed, so the page swiped to keeps its state when it becomes the one on show.
key(item) {
Box(Modifier.fillMaxSize().graphicsLayer { translationX = state.shift + slot * size.width }) {
page(item)
}
}
}
}
}
/** A drag or fling to the left heads for what lies to the right. */
private fun direction(dx: Float): Int = -sign(dx).toInt()
@@ -0,0 +1,151 @@
package eu.lixko.ts3j.client.android.ui
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.selection.selectable
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.myts.MyTeamSpeakSync.Conflict
/**
* Which copy to keep of each item changed both here and in myTeamSpeak since the last
* synchronisation: the item's fields side by side, the ones that differ in bold.
* [onDone] gets whether the user went on; the choices are recorded on the conflicts.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SyncConflictsScreen(conflicts: List<Conflict>, onDone: (Boolean) -> Unit) {
// Mirrors the choices recorded on the conflicts, for recomposition.
val choices = remember(conflicts) {
mutableStateMapOf<Int, Conflict.Choice>().apply {
conflicts.forEachIndexed { i, c -> c.choice()?.let { put(i, it) } }
}
}
fun choose(index: Int, choice: Conflict.Choice) {
conflicts[index].choose(choice)
choices[index] = choice
}
BackHandler { onDone(false) }
Scaffold(
topBar = {
TopAppBar(
title = { Text("Synchronization conflicts") },
navigationIcon = { IconButton(onClick = { onDone(false) }) { Icon(Icons.Filled.Close, "Cancel") } },
)
},
bottomBar = {
Surface(tonalElevation = 3.dp) {
Row(
Modifier.fillMaxWidth().navigationBarsPadding().padding(horizontal = 8.dp, vertical = 8.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Column(Modifier.weight(1f)) {
TextButton(onClick = { conflicts.indices.forEach { choose(it, Conflict.Choice.HERE) } }) {
Text("Keep all of this device's")
}
TextButton(onClick = { conflicts.indices.forEach { choose(it, Conflict.Choice.CLOUD) } }) {
Text("Keep all of myTeamSpeak's")
}
}
Button(onClick = { onDone(true) }, enabled = choices.size == conflicts.size) { Text("Synchronize") }
}
}
},
) { padding ->
LazyColumn(
Modifier.padding(padding),
contentPadding = PaddingValues(16.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
) {
item { Text("Changed here and in myTeamSpeak since the last synchronization:") }
itemsIndexed(conflicts) { index, conflict ->
ConflictCard(conflict, choices[index]) { choose(index, it) }
}
}
}
}
@Composable
private fun ConflictCard(conflict: Conflict, choice: Conflict.Choice?, onChoose: (Conflict.Choice) -> Unit) {
Card(Modifier.fillMaxWidth()) {
Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text((if (conflict.isIdentity) "Identity: " else "Bookmark: ") + conflict.title(),
style = MaterialTheme.typography.titleMedium)
Row {
Spacer(0.3f)
Header(if (conflict.deletedHere()) "This device (deleted)" else "This device")
Header(if (conflict.deletedInCloud()) "myTeamSpeak (deleted)" else "myTeamSpeak")
}
for (d in conflict.differences()) {
Row {
Text(d.label(), Modifier.weight(0.3f), style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant)
Value(if (conflict.deletedHere()) "—" else d.here(), d.differs())
Value(if (conflict.deletedInCloud()) "—" else d.cloud(), d.differs())
}
}
Option(if (conflict.deletedHere()) "Delete" else "Keep this device's", choice == Conflict.Choice.HERE) {
onChoose(Conflict.Choice.HERE)
}
Option(if (conflict.deletedInCloud()) "Delete" else "Keep myTeamSpeak's", choice == Conflict.Choice.CLOUD) {
onChoose(Conflict.Choice.CLOUD)
}
}
}
}
@Composable
private fun androidx.compose.foundation.layout.RowScope.Spacer(weight: Float) {
androidx.compose.foundation.layout.Spacer(Modifier.weight(weight))
}
@Composable
private fun androidx.compose.foundation.layout.RowScope.Header(text: String) {
Text(text, Modifier.weight(0.35f).padding(end = 4.dp), style = MaterialTheme.typography.labelMedium)
}
@Composable
private fun androidx.compose.foundation.layout.RowScope.Value(text: String, differs: Boolean) {
Text(text, Modifier.weight(0.35f).padding(end = 4.dp), style = MaterialTheme.typography.bodySmall,
fontWeight = if (differs) FontWeight.Bold else FontWeight.Normal)
}
@Composable
private fun Option(text: String, selected: Boolean, onClick: () -> Unit) {
Row(
Modifier.fillMaxWidth().selectable(selected, onClick = onClick, role = Role.RadioButton),
verticalAlignment = Alignment.CenterVertically,
) {
RadioButton(selected, onClick = null)
Text(text, Modifier.padding(start = 8.dp))
}
}
@@ -0,0 +1,145 @@
package eu.lixko.ts3j.client.android.ui
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.State
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.android.ServerTree
import eu.lixko.ts3j.client.android.SessionState
/** Clients picked in the tree by a long press, to act on together, and clients being moved while a channel is picked. */
@Stable
internal class TreePicking(
private val server: ServerController,
private val tree: State<ServerTree>,
private val state: State<SessionState>,
) {
/** The clients to move, while a channel for them is being picked. */
var moving by mutableStateOf<Set<Int>?>(null)
private var picked by mutableStateOf(emptySet<Int>())
/** The picked clients still on the server. */
val selection by derivedStateOf { picked.filterTo(LinkedHashSet()) { tree.value.client(it) != null } }
val canPick: Boolean get() = with(server.permissions) { canMoveClients() || canKickFromChannel() || canKickFromServer() }
fun pick(clientId: Int) {
picked = selection + clientId
}
fun toggle(clientId: Int) {
picked = if (clientId in selection) selection - clientId else selection + clientId
}
fun clear() {
picked = emptySet()
}
/** Those of the selection not in our channel. */
val outsideOwnChannel: Set<Int>
get() = selection - tree.value.channel(state.value.channelId)?.clients.orEmpty().map { it.id }.toSet()
/** Whom of the selection a kick goes to: never us, and from a channel, nobody already in the default one. */
fun kickable(fromServer: Boolean): Set<Int> {
val inDefault = if (fromServer) emptySet() else tree.value.channel(server.defaultChannelId)?.clients.orEmpty().map { it.id }.toSet()
return selection - state.value.selfClientId - inDefault
}
fun kick(fromServer: Boolean, reason: String) {
val whom = kickable(fromServer)
if (fromServer) server.kickFromServer(whom, reason) else server.kickFromChannel(whom, reason)
clear()
}
fun moveTo(channelId: Int, clients: Set<Int>) {
server.moveClients(clients, channelId)
moving = null
clear()
}
}
@Composable
internal fun rememberTreePicking(server: ServerController, tree: State<ServerTree>, state: State<SessionState>): TreePicking =
remember(server, tree, state) { TreePicking(server, tree, state) }
/** Above the tree: the clients being moved, or what may be done with those picked. */
@Composable
internal fun PickingBar(picking: TreePicking, server: ServerController, tree: ServerTree, ownChannel: Int, onKick: (fromServer: Boolean) -> Unit) {
val moving = picking.moving
val selection = picking.selection
if (moving != null) {
val clients = moving.mapNotNull { tree.client(it) }
if (clients.isEmpty()) {
LaunchedEffect(moving) { picking.moving = null }
} else {
MovePrompt(clients.singleOrNull()?.name ?: "${clients.size} clients") { picking.moving = null }
}
} else if (selection.isNotEmpty()) {
val can = server.permissions
val outside = picking.outsideOwnChannel
SelectionBar(
count = selection.size,
onMove = if (can.canMoveClients()) ({ picking.moving = selection }) else null,
onMoveHere = if (can.canMoveClients() && outside.isNotEmpty()) ({ picking.moveTo(ownChannel, outside) }) else null,
onKickChannel = if (can.canKickFromChannel() && picking.kickable(false).isNotEmpty()) ({ onKick(false) }) else null,
onKickServer = if (can.canKickFromServer() && picking.kickable(true).isNotEmpty()) ({ onKick(true) }) else null,
onClear = picking::clear,
)
}
}
/** How many clients are picked in the tree, and what may be done with them at once. */
@Composable
private fun SelectionBar(
count: Int,
onMove: (() -> Unit)?,
onMoveHere: (() -> Unit)?,
onKickChannel: (() -> Unit)?,
onKickServer: (() -> Unit)?,
onClear: () -> Unit,
) {
Surface(color = MaterialTheme.colorScheme.secondaryContainer) {
Row(Modifier.fillMaxWidth().padding(horizontal = 4.dp), verticalAlignment = Alignment.CenterVertically) {
IconButton(onClick = onClear) { Icon(Icons.Filled.Close, "Clear selection") }
Text("$count selected", Modifier.weight(1f), maxLines = 1, style = MaterialTheme.typography.bodyMedium)
onMove?.let { IconButton(onClick = it) { PackIcon("CHANNEL_SWITCH", "Move to…") } }
onMoveHere?.let { IconButton(onClick = it) { PackIcon("MOVE_CLIENT_TO_OWN_CHANNEL", "Move to my channel") } }
onKickChannel?.let { IconButton(onClick = it) { PackIcon("KICK_FROM_CHANNEL", "Kick from channel") } }
onKickServer?.let { IconButton(onClick = it) { PackIcon("KICK_FROM_SERVER", "Kick from server") } }
}
}
}
/** Says a channel is being picked for [name] to move to, until it is or [onCancel]. */
@Composable
private fun MovePrompt(name: String, onCancel: () -> Unit) {
Surface(color = MaterialTheme.colorScheme.secondaryContainer) {
Row(Modifier.fillMaxWidth().padding(start = 16.dp, end = 8.dp), verticalAlignment = Alignment.CenterVertically) {
PackIcon("CHANNEL_SWITCH", null)
Text("Move $name to…", Modifier.weight(1f).padding(horizontal = 12.dp), maxLines = 1,
overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodyMedium)
TextButton(onClick = onCancel) { Text("Cancel") }
}
}
}
@@ -0,0 +1,141 @@
package eu.lixko.ts3j.client.android.ui
import android.widget.Toast
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Badge
import androidx.compose.material3.BadgedBox
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.IconButton
import androidx.compose.material3.IconToggleButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.minimumInteractiveComponentSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.dp
import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.android.SessionState
import eu.lixko.ts3j.client.config.Settings
/**
* Mute, deafen, away and the chat, around the push-to-talk button when that is how the
* microphone is used. Holding the mute button switches between push to talk and voice activation.
*/
@Composable
internal fun VoiceBar(
state: SessionState,
/** Whether some server holds the microphone, for push-to-talk to talk on. */
captured: Boolean,
talking: Boolean,
sessions: SessionController,
server: ServerController,
onEnableMicrophone: () -> Unit,
showChat: Boolean,
unread: Boolean,
onChat: () -> Unit,
) {
val context = LocalContext.current
val ptt = state.connected && captured && state.inputMode == Settings.InputMode.PUSH_TO_TALK
val mic = @Composable {
BarButton(
onClick = { server.setMicMuted(!state.micMuted) },
onLongClick = {
val mode = sessions.toggleInputMode()
val text = if (mode == Settings.InputMode.PUSH_TO_TALK) "Switched to push-to-talk mode."
else "Switched to voice activation mode."
Toast.makeText(context, text, Toast.LENGTH_SHORT).show()
},
enabled = state.connected,
) {
if (state.micMuted) PackIcon("INPUT_MUTED", "Unmute microphone")
else PackIcon("CAPTURE", "Mute microphone")
}
}
val deafen = @Composable {
IconToggleButton(state.deafened, { server.setDeafened(it) }, enabled = state.connected) {
if (state.deafened) PackIcon("OUTPUT_MUTED", "Undeafen")
else PackIcon("PLAYBACK", "Deafen")
}
}
// Another server holds the microphone.
val activate = @Composable {
if (state.connected && state.micPermission && !state.micActive) {
IconButton(onClick = onEnableMicrophone) { PackIcon("ACTIVATE_MICROPHONE", "Speak on this server") }
}
}
val middle = @Composable {
when {
ptt -> PushToTalk(talking, sessions::setPushToTalk, Modifier.fillMaxWidth().height(48.dp))
!state.micPermission -> FilledTonalButton(onClick = onEnableMicrophone) {
PackIcon("CAPTURE", null)
Text("Use microphone", Modifier.padding(start = 8.dp), maxLines = 1)
}
}
}
val away = @Composable {
IconToggleButton(state.away, { server.setAway(it) }, enabled = state.connected) {
PackIcon("AWAY", if (state.away) "Back" else "Away", Modifier.alpha(if (state.away) 1f else 0.5f))
}
}
val chat = @Composable {
IconToggleButton(showChat, { onChat() }) {
BadgedBox(badge = { if (unread && !showChat) Badge() }) {
PackIcon(listOf("MESSAGES", "CHANNEL_CHAT"), if (showChat) "Channels" else "Chat",
Modifier.alpha(if (showChat) 1f else 0.7f))
}
}
}
Surface(tonalElevation = 3.dp) {
// The same places whatever shows: sides of three buttons each keep the talk button centred.
Row(Modifier.fillMaxWidth().navigationBarsPadding().padding(horizontal = 8.dp, vertical = 4.dp),
horizontalArrangement = Arrangement.spacedBy(4.dp),
verticalAlignment = Alignment.CenterVertically) {
Row(Modifier.width(SIDE), verticalAlignment = Alignment.CenterVertically) {
Slot { mic() }; Slot { deafen() }; Slot { activate() }
}
Box(Modifier.weight(1f).height(48.dp), contentAlignment = Alignment.Center) { middle() }
Row(Modifier.width(SIDE), horizontalArrangement = Arrangement.End, verticalAlignment = Alignment.CenterVertically) {
Slot { away() }; Slot { chat() }
}
}
}
}
private val SLOT = 48.dp
private val SIDE = SLOT * 3
/** One button's place in the bar, kept whether or not the button shows. */
@Composable
private fun Slot(content: @Composable () -> Unit) {
Box(Modifier.size(SLOT), contentAlignment = Alignment.Center) { content() }
}
/** An icon button that also answers a long press. */
@Composable
private fun BarButton(onClick: () -> Unit, onLongClick: () -> Unit, enabled: Boolean, content: @Composable () -> Unit) {
Box(
Modifier
.minimumInteractiveComponentSize()
.size(40.dp)
.clip(CircleShape)
.combinedClickable(enabled = enabled, role = Role.Button, onLongClick = onLongClick, onClick = onClick)
.alpha(if (enabled) 1f else 0.38f),
contentAlignment = Alignment.Center,
) { content() }
}
@@ -39,8 +39,8 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.lixko.ts3j.client.android.ServerController import eu.lixko.ts3j.client.android.ServerController
import eu.lixko.ts3j.client.android.SessionController
import eu.lixko.ts3j.client.android.SessionState import eu.lixko.ts3j.client.android.SessionState
import eu.lixko.ts3j.client.android.WhisperListManager
import eu.lixko.ts3j.client.config.WhisperList import eu.lixko.ts3j.client.config.WhisperList
import eu.lixko.ts3j.client.net.Whisper import eu.lixko.ts3j.client.net.Whisper
@@ -65,8 +65,8 @@ fun WhisperBanner(state: SessionState, onStop: () -> Unit) {
/** The top bar's whisper button: a list to whisper to, a reply to the last whisper, the lists' editor. */ /** The top bar's whisper button: a list to whisper to, a reply to the last whisper, the lists' editor. */
@Composable @Composable
fun WhisperMenu(vm: SessionController, server: ServerController, state: SessionState, onManage: () -> Unit) { fun WhisperMenu(whisperLists: WhisperListManager, server: ServerController, state: SessionState, onManage: () -> Unit) {
val lists by vm.whisperLists.collectAsStateWithLifecycle() val lists by whisperLists.all.collectAsStateWithLifecycle()
var open by remember { mutableStateOf(false) } var open by remember { mutableStateOf(false) }
Box { Box {
IconButton(onClick = { open = true }) { PackIcon("WHISPER", "Whisper") } IconButton(onClick = { open = true }) { PackIcon("WHISPER", "Whisper") }
@@ -95,8 +95,8 @@ fun WhisperMenu(vm: SessionController, server: ServerController, state: SessionS
/** Picks the whisper list to add something to, or names a new one. */ /** Picks the whisper list to add something to, or names a new one. */
@Composable @Composable
fun AddToWhisperListDialog(vm: SessionController, what: String, onDismiss: () -> Unit, onPick: (index: Int, newName: String) -> Unit) { fun AddToWhisperListDialog(whisperLists: WhisperListManager, what: String, onDismiss: () -> Unit, onPick: (index: Int, newName: String) -> Unit) {
val lists by vm.whisperLists.collectAsStateWithLifecycle() val lists by whisperLists.all.collectAsStateWithLifecycle()
var naming by remember { mutableStateOf(false) } var naming by remember { mutableStateOf(false) }
if (naming) { if (naming) {
TextPrompt("New whisper list", "Name", "Add", onDismiss = onDismiss, onConfirm = { TextPrompt("New whisper list", "Name", "Add", onDismiss = onDismiss, onConfirm = {
@@ -123,12 +123,12 @@ fun AddToWhisperListDialog(vm: SessionController, what: String, onDismiss: () ->
/** The saved whisper lists, each opening onto its channels and clients. */ /** The saved whisper lists, each opening onto its channels and clients. */
@Composable @Composable
fun WhisperListsScreen(vm: SessionController, server: ServerController, onBack: () -> Unit) { fun WhisperListsScreen(whisperLists: WhisperListManager, server: ServerController, onBack: () -> Unit) {
val lists by vm.whisperLists.collectAsStateWithLifecycle() val lists by whisperLists.all.collectAsStateWithLifecycle()
/** The list being edited: its index, -1 for a new one; null on the overview. */ /** The list being edited: its index, -1 for a new one; null on the overview. */
var editing by rememberSaveable { mutableStateOf<Int?>(null) } var editing by rememberSaveable { mutableStateOf<Int?>(null) }
editing?.let { index -> editing?.let { index ->
WhisperListScreen(vm, server, index, lists.getOrNull(index) ?: WhisperList(), onBack = { editing = null }) WhisperListScreen(whisperLists, server, index, lists.getOrNull(index) ?: WhisperList(), onBack = { editing = null })
return return
} }
SubScreen("Whisper lists", onBack = onBack, actions = { SubScreen("Whisper lists", onBack = onBack, actions = {
@@ -156,7 +156,7 @@ fun WhisperListsScreen(vm: SessionController, server: ServerController, onBack:
server.setWhisper(Whisper.of(list)) server.setWhisper(Whisper.of(list))
onBack() onBack()
}) })
DropdownMenuItem({ Text("Remove") }, onClick = { menu = false; vm.removeWhisperList(index) }) DropdownMenuItem({ Text("Remove") }, onClick = { menu = false; whisperLists.remove(index) })
} }
} }
}, },
@@ -177,7 +177,7 @@ private fun summary(list: WhisperList): String {
/** One whisper list: its name, channels and clients, saved on Save. */ /** One whisper list: its name, channels and clients, saved on Save. */
@Composable @Composable
private fun WhisperListScreen(vm: SessionController, server: ServerController, index: Int, saved: WhisperList, onBack: () -> Unit) { private fun WhisperListScreen(whisperLists: WhisperListManager, server: ServerController, index: Int, saved: WhisperList, onBack: () -> Unit) {
var name by rememberSaveable { mutableStateOf(saved.name) } var name by rememberSaveable { mutableStateOf(saved.name) }
var list by remember { mutableStateOf(saved.copy()) } var list by remember { mutableStateOf(saved.copy()) }
val change = { f: WhisperList.() -> Unit -> list = list.copy().apply(f) } val change = { f: WhisperList.() -> Unit -> list = list.copy().apply(f) }
@@ -186,7 +186,7 @@ private fun WhisperListScreen(vm: SessionController, server: ServerController, i
SubScreen(if (index < 0) "New whisper list" else "Edit whisper list", onBack = onBack, actions = { SubScreen(if (index < 0) "New whisper list" else "Edit whisper list", onBack = onBack, actions = {
TextButton(onClick = { TextButton(onClick = {
vm.saveWhisperList(index, list.copy().apply { this.name = name.trim() }) whisperLists.save(index, list.copy().apply { this.name = name.trim() })
onBack() onBack()
}, enabled = name.isNotBlank()) { Text("Save") } }, enabled = name.isNotBlank()) { Text("Save") }
}) { padding -> }) { padding ->
@@ -1,6 +1,6 @@
package eu.lixko.ts3j.client.android.audio; package eu.lixko.ts3j.client.android.audio;
import eu.lixko.ts3j.client.audio.opus.CtlOpusEncoder; import eu.lixko.ts3j.client.audio.opus.AbstractCtlOpusEncoder;
import eu.lixko.ts3j.client.audio.opus.LibOpus; import eu.lixko.ts3j.client.audio.opus.LibOpus;
import eu.lixko.ts3j.client.audio.opus.OpusCodec; import eu.lixko.ts3j.client.audio.opus.OpusCodec;
import eu.lixko.ts3j.client.audio.opus.OpusDecoder; import eu.lixko.ts3j.client.audio.opus.OpusDecoder;
@@ -29,7 +29,7 @@ public final class NativeOpus implements OpusCodec {
} }
/** Methods may come from different threads, one at a time, so they only share the handle. */ /** Methods may come from different threads, one at a time, so they only share the handle. */
private static final class Encoder extends CtlOpusEncoder { private static final class Encoder extends AbstractCtlOpusEncoder {
private final int frameSize; private final int frameSize;
private long handle; private long handle;
+33
View File
@@ -0,0 +1,33 @@
# Structural audit — ts3-client and Android
Audit: 2026-10-11. Design and maintainability (DRY, SOLID, separation of concerns); the
correctness audit is [AUDIT.md](AUDIT.md). Not reviewed: the audio/DSP packages, tray/X11,
D-Bus and the ts3j submodule.
Items are worked through in the order below. Status: open, done (commit), or closed (reason).
| # | Finding | Status |
|---|---|---|
| 1 | Request failures reach frontends as strings, so they guess the kind by substring (`BanListDialog`, `ServerLogDialog`) and core needs a sentinel message (`SEARCH_NOT_PERMITTED`); success is signalled by a `null` error, here and in Android's `ServerController` (`String?`) | done (`0552ed8`): requests return `CompletableFuture`, failing with `RequestException` (kind + message); `Replies`/`Edt` split success and failure; Android uses `Result` |
| 2 | Client properties parsed twice: `ConnectionEventHandler.onClientJoin` sets every field, `onClientChanged` the same ones again; channels already share `applyChannelProperties` | done (`e255a46`): one `applyClientProperties`. It also fixed a joining channel commander shown as none, and picks up the description a client enters with |
| 3 | What we may do is answered in five places: `ServerSession.can*`, `ServerModel.can*/permits/mayHavePower`, `TeamspeakConnection.canSendOfflineMessages/canTransferFiles`, and raw permission names in Swing dialogs and `ServerController.canCreateBans` | done (`13e3a62`): `Permissions` owns the table, the rules and one named question per capability; `ServerSession.permissions()` is `NONE` while disconnected; no permission names outside core except channel-permission editing |
| 4 | `TeamspeakConnection` (2,157 lines) still does lifecycle, mic/speaker, recording, chat logs, log/sound text, contacts, avatars, icons, file transfers, myTeamSpeak and job plumbing. The `*Admin` helpers take the whole connection, which forwards ~90 methods to them | done, in sub-steps (now 841 lines): |
| 4a | … chat log and what we tell the user (log lines, sounds, links and sound variables) | done (`1bc7eb5`): `ChatLog`, `Announcer` |
| 4b | … request plumbing into its own class; `*Admin` helpers on narrow dependencies instead of the whole connection | done (`da908f7`; renamed `Uplink` in 4c, as `session.ServerLink` is the `ts3server://` link): `ServerLink` owns the socket, event and request threads and file transfers, and runs requests; the helpers take it (plus the model, permissions or avatars where they need them) |
| 4c | … frontends reach the admin helpers directly instead of ~40 one-line forwarders | done (`959f7ed`): the helpers are public with non-blocking methods, reached through `ServerSession`/`TeamspeakConnection` getters; 30 forwarders gone, and what they added (stop-at-first-refusal loops, log lines, description refresh, own avatar flag) moved into the helpers. Swing dialogs still take the whole connection for the model and our ids (item 5) |
| 4d | … our own state (mic, speakers, away, talk request, recording) out of the connection | done (`9107bdd`): `OwnClient` owns the devices and our flags, and publishes them; `Recording` the recorder. `ServerSession` no longer keeps its own copy of the flags, and they are cleared when a connect starts rather than once it is done |
| 5 | Two front doors: frontends use both `ServerSession` and `session.connection()` with no rule for which | done (`de42429`): `connection()` is gone; frontends reach the model, our ids, devices and the helpers through `ServerSession`. New helpers took the remaining actions off the connection: `ClientAdmin` (move, kick, ban, groups, talk power, poke, details), `ChannelFiles`, `ClientContacts`; `ChannelAdmin` also joins, moves and subscribes. Dialogs take the session, or only the helper they use |
| 6 | Menu bar, toolbar and hotkeys each implement the same commands: `MainMenuBar.Listener` (~50 methods, ~210 lines of forwarding in `MainFrame`), `MainToolbar.Listener`, `HotkeyActions` | done (`f7cf040`): `MainCommands` holds each command once, acting on the server on screen or, for hotkeys, on a list of sessions; the menu, toolbar and hotkeys call it directly and both `Listener` interfaces are gone. The menu's mute items no longer click the toolbar's buttons, and the menu's commander toggle now repaints the toolbar and tray |
| 7 | The admin list dialogs (bans, complaints, offline messages, privilege keys, server log) repeat the load/status/table-model scaffolding | done (`e214f21`): the five extend `AbstractServerListDialog`, which lays out the toolbar, list, status line and Reload/Close, follows the server's name, binds F5/Ctrl+W/Escape, guards loading, reloads after a change and reports its failure; `ServerTab` keeps them in one map. All five now take F5, show load failures in red, and keep the status line's height; the ban list's own placeholder field is FlatLaf's. The table models stay per dialog: their rows and columns share nothing |
| 8 | `Settings`: 58 public fields, each key spelled twice (load and save), no change notification, so callers fan changes out by hand | done (`203082d`): each value is a `Setting<T>` (`get`/`set`, listeners), declared once with its key, type and range, and loaded and saved from that list. Output device, volume and receive buffer reach every connection, and the status bar and master volume slider follow their toggles, through listeners instead of calls at each place that changes them; Android puts output settings and country flags into effect the same way. `SplitRatio` takes the setting itself. The sections with their own load/store (row colours, server log, notifications, contact defaults) are unchanged. The Playback page now previews the voice volume with the master volume applied, as Apply sets it |
| 9 | Duplicates: three byte-size formatters (`FileBrowserDialog`, `ChatHtml`, `ConnectionStatsFormat`); four "which chat" enums (`ChatScope`, `ChatLogScope`, `ChatPanel.Target`, Android `ChatKey`); the conversation model lives in each frontend | done, in sub-steps: |
| 9a | … byte-size formatters | done (`5358599`): `text.ByteSize` writes sizes and rates as TeamSpeak does (`1023 Bytes`, `353.98 KiB`); chat attachments and the file browser now use it too, so they show KiB/MiB with two decimals |
| 9b | … "which chat" enums | done (`5358599`): one `chat.ChatScope` replaces `ConnectionListener.ChatScope`, `ChatLogScope` and `ChatPanel.Target`, and the mappings between them are gone. Android's `ChatKey` also carries the peer, so it goes with the conversation model |
| 9c | … the conversation model (Swing `ChatPanel.Tab`, Android `Chats`) | done (`a2a1280`): `session.ChatFeed` decides which conversation a message, history or server event goes to and renders it, and the frontends get the lines through `chat.ChatSink` (`ServerSession.Listener` no longer passes on raw chat events). `chat.ChatKey` replaces Android's own key and `ChatPanel`'s scope and client id. Each frontend still keeps and draws the lines its own way. Fixes Swing labelling our messages with the global nickname instead of the one we have on the server, and linking our name in a private chat to the peer |
| 10 | Android `ServerScreen`: one 456-line composable holding ~25 pieces of state | done (`78b66ef`): `ServerNav` holds where the screen is (one saved `ServerPage` for the five pages that replace it, tree or chat, the conversation, and one `Overlay` for the eight sheets and dialogs); `TreeView` and `ChatSearch` the find state of each side; `TreePicking` the long-press selection and moves. The sheets and dialogs are `ServerOverlay`; `VoiceBar` and `ServerSwitcher` have their own files. Only one sheet or dialog shows at a time, so a channel link in a client sheet now replaces it; Find in tree from a sheet honours Only matches; a failed channel deletion's snackbar is no longer cancelled with its dialog |
| 11 | Android `SessionController` (669 lines) is the app-wide view model and service locator; every screen gets all of it | done, in sub-steps: |
| 11a | … the app-wide stores out of it, and screens on the parts they use | done (`382d76c`): `AppParts` wires what lives as long as the process; `BookmarkManager`, `ContactManager`, `WhisperListManager`, `MyTeamSpeakAccount` (sign-in, import, chat attachments) and `AudioSetup` (route, devices, sound packs, floating PTT button) hold what was in `SessionController`, which keeps the servers, the microphone between them and the voice settings (386 lines, with `SessionState` and `SessionEvent`). Leaf screens take only their parts; `App` and the settings hub take `AppParts`. Country flags and description pictures are set on `Settings` directly |
| 11b | … `ServerController` on narrow dependencies instead of the whole `SessionController`, which still forwards the stores to it | done (`6070160`): `ServerParts` holds what every server shares (settings, identities, audio, contacts, myTeamSpeak, notifier, network) and builds its `ServerSession`; `SessionController` lost its pass-throughs and audio setup (`AppParts` builds the `LevelMonitor`). `ServerController` reports back to its owner directly: it has one, so no callback interface |
| 12 | Swing `ui` package: 118 files, flat | done (`7e794ff`): by feature. `ui` keeps the main window and what is app-wide (frame, commands, menus, toolbar, status bar, tabs, tray, notifications, look-and-feel, window placement); `ui.server` one server's tab (tree, info, context menus and their actions, file browser, connection info); `ui.chat` the chat and the HTML views (pictures, links, zoom); `ui.admin` moderation and the server's list windows; `ui.channel` the channel editor; `ui.options` the Options pages; `ui.hotkey` hotkeys; `ui.manage` bookmarks, contacts, identities and connecting; `ui.icons`; `ui.widget` the shared Swing bits (`Dialogs`, `Edt`, `FindBar`, `FormPanel`, …). What another package uses became public (~200 declarations); nothing else changed. The app icons moved to `ui/icons` with `Icons` |
| 13 | `ClientEntry`/`ChannelNode` are bags of public volatile fields; a reader can see a half-applied update | deferred: each field is `volatile`, so a reader sees only a moment's mix of old and new on a multi-field read, which the next update repaints; it has caused no bug. If one does, a `ServerModel` lock around each event's properties and the few multi-field readers (tree snapshot and renderer, info, details) fixes it without touching the ~1,000 field accesses |
| 14 | Core produces English UI copy (status lines, log lines) | deferred until the app is translated: both frontends show the same English, so core keeps it written once; the chat log lines are TS3's own and go to disk from core regardless. Translating would start with status lines and error prefixes as structured events, and `SelfState`/`HotkeyAction` labels in each frontend's string resources |
+17
View File
@@ -2,6 +2,7 @@
First audit: 2026-09-11. Revisited and worked through: 2026-09-25. Every finding below was First audit: 2026-09-11. Revisited and worked through: 2026-09-25. Every finding below was
either fixed (commit given) or closed with a reason. Logging (§3) was left out on purpose. either fixed (commit given) or closed with a reason. Logging (§3) was left out on purpose.
The structural audit of 2026-10-11 is [AUDIT-STRUCTURE.md](AUDIT-STRUCTURE.md).
State after the fixes: `mvn -o test` passes (177 tests: 25 in ts3j, 135 core, 11 desktop, State after the fixes: `mvn -o test` passes (177 tests: 25 in ts3j, 135 core, 11 desktop,
6 swing), on Java 25 and 26. The Android release build (R8 over core and ts3j) passes. The 6 swing), on Java 25 and 26. The Android release build (R8 over core and ts3j) passes. The
@@ -71,6 +72,22 @@ chat logs, and wrote its profile owner-only.
- **Not tested:** `TeamspeakConnection`'s lifecycle against a fake socket (the smoke test - **Not tested:** `TeamspeakConnection`'s lifecycle against a fake socket (the smoke test
above covers connect only); the idle release and dead-line replacement in above covers connect only); the idle release and dead-line replacement in
`PerSpeakerPlayout`; the jitter buffer with real voice from another client. `PerSpeakerPlayout`; the jitter buffer with real voice from another client.
- **Open (found 2026-10-14): an upload counts as completed before the server has the file.**
`FileTransferManager.runUpload` marks the transfer completed once the last bytes are flushed
to the file socket; the server may still be receiving them. A listing taken right then shows
a partial size (seen on the local 3.13.7 server: 241,664 of 300,000 bytes; a moment later
the full size, and a download got every byte). The file browser's refresh after an upload
can hit this. Fix: before `markCompleted`, wait for the server to confirm, either
- the `notifystatusfiletransfer` for the transfer's `clientftfid` with the "transfer
complete" status (believed to be 2065, not yet seen here); `handleFileTransferEvent`
already parses it but only routes it to `pendingInits` during negotiation, so keep a
waiter registered until the upload ends; or
- the file server closing the connection: `shutdownOutput()`, then read to EOF;
whichever the server is shown to do first (watch what it sends after an upload). Bound the
wait (a few seconds), then mark completed anyway, so a server that never confirms does not
leave uploads stuck at 100 %. About 15–30 lines in core; both frontends follow. A check
that lists the file from a second client right after the upload completes reproduces it.
- **`git stash@{0}`** ("jitter buffer test") is now fully ported, except FEC decoding (TS3 - **`git stash@{0}`** ("jitter buffer test") is now fully ported, except FEC decoding (TS3
does not use FEC either). It can be dropped. does not use FEC either). It can be dropped.
+26 -8
View File
@@ -66,6 +66,10 @@ Android app in [`../android`](../android) does.
on demand); selecting a client shows its **server groups** and **channel group** on demand); selecting a client shows its **server groups** and **channel group**
(names resolved from the server's group lists), talk power, platform and version. (names resolved from the server's group lists), talk power, platform and version.
- **Server-group badge** next to each client's nickname in the tree. - **Server-group badge** next to each client's nickname in the tree.
- **Talk power** — request it (Self menu, with a reason, or a hotkey); grant or revoke
it from a client's menu, or grant the next request in our channel by hotkey. The
tree marks granted clients, those short of the channel's needed talk power, and
pending requests, whose reason shows in the info panel.
- **Spacer channels** — TS3 `[spacer]`/`[*spacer]`/`[c/l/r spacer]` names render as - **Spacer channels** — TS3 `[spacer]`/`[*spacer]`/`[c/l/r spacer]` names render as
non-interactive separators (fill, centred, aligned). non-interactive separators (fill, centred, aligned).
- Double-click a channel to **join**; right-click a client to **poke**, open a - Double-click a channel to **join**; right-click a client to **poke**, open a
@@ -112,6 +116,10 @@ Android app in [`../android`](../android) does.
- **Self status** — Away (with message) and Channel Commander toggles. - **Self status** — Away (with message) and Channel Commander toggles.
- **Status bar** shows the server name, user count and live ping. - **Status bar** shows the server name, user count and live ping.
- Change your nickname, mute/deafen from the toolbar. - Change your nickname, mute/deafen from the toolbar.
- **Customize Toolbar** (right-click the toolbar), as in TeamSpeak 3: pick, order and
separate the buttons from ~70 actions (connection, self, dialogs, permissions,
recording, and channel/client actions on the tree's selection); search, drag and drop,
Reset to Defaults.
### Hotkeys ### Hotkeys
- **Global hotkeys**, as in TeamSpeak 3: single keys or combinations (any key can act - **Global hotkeys**, as in TeamSpeak 3: single keys or combinations (any key can act
@@ -222,16 +230,21 @@ core/ eu.lixko.ts3j.client
│ AwayMessages, …; AppDirs finds it, ProfileFiles writes it │ AwayMessages, …; AppDirs finds it, ProfileFiles writes it
│ privately and all at once │ privately and all at once
├── session ├── session
│ ├── ServerSession one server tab's state and actions, whatever the frontend │ ├── ServerSession one server tab's state and actions, whatever the frontend;
│ │ the frontends' only way in to a server
│ ├── ChatFeed turns chat events into the lines of each conversation
│ └── Sessions what the servers share: the microphone, away state, nickname │ └── Sessions what the servers share: the microphone, away state, nickname
├── net ├── net
│ ├── TeamspeakConnection ties socket + audio + model; runs requests on its own pool │ ├── TeamspeakConnection ties socket + audio + model; the connection lifecycle
│ ├── ConnectionEventHandler server events → model changes, sounds and log lines │ ├── ConnectionEventHandler server events → model changes, sounds and log lines
│ ├── ServerModel channel/client state; ChannelNode/ClientEntry view models │ ├── ServerModel channel/client state; ChannelNode/ClientEntry view models
│ ├── ChannelAdmin/BanAdmin/AvatarAdmin channel editing, the ban list, our own avatar │ ├── ClientAdmin/ChannelAdmin what we do to clients and channels
│ ├── BanAdmin/AvatarAdmin/… the ban list, our own avatar and the other admin lists
│ ├── ChannelFiles channel file browsing, up- and downloads
│ ├── ClientContacts the contact list applied to a server's clients
│ ├── IconRepository server icons (avatar/ holds the client avatar cache) │ ├── IconRepository server icons (avatar/ holds the client avatar cache)
│ ├── filetransfer channel file browsing, up- and downloads │ ├── filetransfer the file transfer protocol
│ └── ConnectionListener frontend callbacks │ └── ConnectionListener what the connection tells its session
├── audio the voice pipelines every platform shares ├── audio the voice pipelines every platform shares
│ ├── AudioBackend/AudioIo what a platform supplies: devices, lines, Opus │ ├── AudioBackend/AudioIo what a platform supplies: devices, lines, Opus
│ ├── CaptureVoiceInput capture → processing → VAD/PTT gate → Opus encode │ ├── CaptureVoiceInput capture → processing → VAD/PTT gate → Opus encode
@@ -241,9 +254,10 @@ core/ eu.lixko.ts3j.client
│ ├── processing port of TS3's WebRTC capture chain: HPF, NS, transients, AGC2 │ ├── processing port of TS3's WebRTC capture chain: HPF, NS, transients, AGC2
│ ├── vad port of WebRTC's rnn_vad speech detector │ ├── vad port of WebRTC's rnn_vad speech detector
│ └── opus codec interfaces │ └── opus codec interfaces
├── chat ChatKey/ChatScope: which conversation; ChatSink: where its lines go
├── chatlog TS3-compatible chat logs, shared with the TS3 client by default ├── chatlog TS3-compatible chat logs, shared with the TS3 client by default
├── contacts friends and blocked clients, in TS3's own record format ├── contacts friends and blocked clients, in TS3's own record format
├── text BBCode, TeamSpeak links, chat search ├── text BBCode, TeamSpeak links, chat search, byte sizes
├── gfx ├── gfx
│ ├── IconPack an icon pack zip/folder/classpath folder + its settings.ini mapping │ ├── IconPack an icon pack zip/folder/classpath folder + its settings.ini mapping
│ ├── IconPacks discovery of installed packs, the shipped Material one, lookup order │ ├── IconPacks discovery of installed packs, the shipped Material one, lookup order
@@ -288,6 +302,9 @@ swing/ eu.lixko.ts3j.client
├── Main entry point (look & feel, settings, backend injection) ├── Main entry point (look & feel, settings, backend injection)
└── ui └── ui
├── MainFrame window: menu, toolbar, tree | chat, status bar ├── MainFrame window: menu, toolbar, tree | chat, status bar
├── MainCommands what the menu, toolbar and hotkeys do, each command once
├── ToolbarActions what the toolbar can show (ToolbarAction), laid out per ToolbarLayout
├── CustomizeToolbarDialog picks and orders the toolbar's buttons
├── ServerTreePanel TS3-style channel/client tree (group badges, spacers) ├── ServerTreePanel TS3-style channel/client tree (group badges, spacers)
├── Spacers TS3 spacer-channel name parsing/rendering ├── Spacers TS3 spacer-channel name parsing/rendering
├── InfoPanel channel description / client group + details view ├── InfoPanel channel description / client group + details view
@@ -296,13 +313,14 @@ swing/ eu.lixko.ts3j.client
├── HotkeysPanel hotkey list (Options → Hotkeys) ├── HotkeysPanel hotkey list (Options → Hotkeys)
├── HotkeyDialog add/edit one hotkey: action, combination, trigger, scope ├── HotkeyDialog add/edit one hotkey: action, combination, trigger, scope
├── HotkeyService bindings + engine + input hook, for the dialogs ├── HotkeyService bindings + engine + input hook, for the dialogs
├── HotkeyActions carries a fired hotkey out on the client ├── HotkeyActions maps a fired hotkey to its command
├── NotificationsPanel sound pack + per-action sound/important configuration ├── NotificationsPanel sound pack + per-action sound/important configuration
├── IconPackPanel icon pack chooser + icon viewer (Options → Design) ├── IconPackPanel icon pack chooser + icon viewer (Options → Design)
├── DisplayScale interface scale on Linux (fractional, via FlatLaf) ├── DisplayScale interface scale on Linux (fractional, via FlatLaf)
├── ConnectDialog connect form ├── ConnectDialog connect form
├── BookmarksDialog manage saved servers ├── BookmarksDialog manage saved servers
├── IdentitiesDialog manage identities (new/import/export/improve) ├── IdentitiesDialog manage identities (new/import/export/improve)
├── AbstractServerListDialog shared frame of a server's list windows (bans, complaints, privilege keys, offline messages, server log)
├── IdentityChooser identity drop-down shared by connect/bookmark forms ├── IdentityChooser identity drop-down shared by connect/bookmark forms
├── LevelMeter dBFS meter with threshold marker ├── LevelMeter dBFS meter with threshold marker
├── IconTheme active icon pack: rasterising (JSVG) and caching ├── IconTheme active icon pack: rasterising (JSVG) and caching
@@ -314,7 +332,7 @@ swing/ eu.lixko.ts3j.client
- Whisper is received/played but not yet **sendable** from the UI. - Whisper is received/played but not yet **sendable** from the UI.
- Hotkey actions TeamSpeak offers but this client does not perform yet (listed but - Hotkey actions TeamSpeak offers but this client does not perform yet (listed but
greyed out in the dialog): capture/playback/hotkey profiles and sound packs, greyed out in the dialog): capture/playback/hotkey profiles and sound packs,
whisper and push-to-whisper, recording, plugins, server groups, talk power, 3D whisper and push-to-whisper, recording, plugins, server groups, 3D
sound, hardware ("local") microphone mute and the channel-traversal variants sound, hardware ("local") microphone mute and the channel-traversal variants
beyond "Switch to Channel". beyond "Switch to Channel".
- Global hotkeys cover Linux and Windows; **macOS has no backend**, so hotkeys there are - Global hotkeys cover Linux and Windows; **macOS has no backend**, so hotkeys there are
@@ -24,12 +24,12 @@ public interface AudioBackend {
} }
default VoiceOutput createOutput(Settings settings) { default VoiceOutput createOutput(Settings settings) {
return new StreamingVoiceOutput(io(), opus(), settings.outputDevice, outputLines()); return new StreamingVoiceOutput(io(), opus(), settings.outputDevice.get(), outputLines());
} }
/** Player for notification sounds (sound packs); shared by all connections. */ /** Player for notification sounds (sound packs); shared by all connections. */
default SoundPlayer createSoundPlayer(Settings settings) { default SoundPlayer createSoundPlayer(Settings settings) {
return new PackSoundPlayer(io(), opus(), settings.outputDevice); return new PackSoundPlayer(io(), opus(), settings.outputDevice.get());
} }
/** Human-readable codec/backend description, e.g. for an "about" line. */ /** Human-readable codec/backend description, e.g. for an "about" line. */
@@ -103,21 +103,21 @@ public final class CaptureVoiceInput implements VoiceInput {
public CaptureVoiceInput(Settings settings, AudioIo io, OpusCodec opus) { public CaptureVoiceInput(Settings settings, AudioIo io, OpusCodec opus) {
this.io = io; this.io = io;
this.opus = opus; this.opus = opus;
this.deviceName = settings.inputDevice; this.deviceName = settings.inputDevice.get();
this.mode = settings.inputMode; this.mode = settings.inputMode.get();
this.vadMode = settings.vadMode; this.vadMode = settings.vadMode.get();
this.thresholdDb = settings.vadThresholdDb; this.thresholdDb = settings.vadThresholdDb.get();
this.speechThreshold = settings.speechThreshold; this.speechThreshold = settings.speechThreshold.get();
this.vadOverPtt = settings.vadOverPtt; this.vadOverPtt = settings.vadOverPtt.get();
this.inputGain = settings.inputVolume; this.inputGain = settings.inputVolume.get();
this.params = OpusParameters.from(settings); this.params = OpusParameters.from(settings);
this.codec = codecFor(params); this.codec = codecFor(params);
setRedundancy(settings.redundancyDelay, settings.redundancyCopies); setRedundancy(settings.redundancyDelay.get(), settings.redundancyCopies.get());
processor.setNoiseSuppression(settings.denoise); processor.setNoiseSuppression(settings.denoise.get());
processor.setSuppressionLevel(SuppressionLevel.fromDenoiserLevel(settings.denoiserLevel)); processor.setSuppressionLevel(SuppressionLevel.fromDenoiserLevel(settings.denoiserLevel.get()));
processor.setTransientSuppression(settings.typingAttenuation); processor.setTransientSuppression(settings.typingAttenuation.get());
processor.setGainControl(settings.agc); processor.setGainControl(settings.agc.get());
processor.setGainBoost(settings.agcBoostDb); processor.setGainBoost(settings.agcBoostDb.get());
} }
// ---- live configuration (safe to call from the UI thread) ---- // ---- live configuration (safe to call from the UI thread) ----
@@ -9,7 +9,8 @@ import eu.lixko.ts3j.client.config.Settings;
public final class OpusParameters { public final class OpusParameters {
public static OpusParameters from(Settings s) { public static OpusParameters from(Settings s) {
return new OpusParameters(s.bitrate, s.complexity, s.vbr, s.fec, s.packetLoss, s.music); return new OpusParameters(s.bitrate.get(), s.complexity.get(), s.vbr.get(), s.fec.get(), s.packetLoss.get(),
s.music.get());
} }
/** Target bitrate in bits per second. */ /** Target bitrate in bits per second. */
@@ -92,19 +92,19 @@ public interface VoiceInput extends Microphone {
/** Takes on the voice settings, as they stand now, while capturing. */ /** Takes on the voice settings, as they stand now, while capturing. */
default void apply(Settings settings) { default void apply(Settings settings) {
setInputDevice(settings.inputDevice); setInputDevice(settings.inputDevice.get());
setMode(settings.inputMode); setMode(settings.inputMode.get());
setVadMode(settings.vadMode); setVadMode(settings.vadMode.get());
setThresholdDb(settings.vadThresholdDb); setThresholdDb(settings.vadThresholdDb.get());
setSpeechThreshold(settings.speechThreshold); setSpeechThreshold(settings.speechThreshold.get());
setVadOverPtt(settings.vadOverPtt); setVadOverPtt(settings.vadOverPtt.get());
setInputGain(settings.inputVolume); setInputGain(settings.inputVolume.get());
setNoiseSuppression(settings.denoise); setNoiseSuppression(settings.denoise.get());
setDenoiserLevel(settings.denoiserLevel); setDenoiserLevel(settings.denoiserLevel.get());
setTypingAttenuation(settings.typingAttenuation); setTypingAttenuation(settings.typingAttenuation.get());
setAgc(settings.agc); setAgc(settings.agc.get());
setAgcBoost(settings.agcBoostDb); setAgcBoost(settings.agcBoostDb.get());
setOpusParameters(OpusParameters.from(settings)); setOpusParameters(OpusParameters.from(settings));
setRedundancy(settings.redundancyDelay, settings.redundancyCopies); setRedundancy(settings.redundancyDelay.get(), settings.redundancyCopies.get());
} }
} }
@@ -1,7 +1,7 @@
package eu.lixko.ts3j.client.audio.opus; package eu.lixko.ts3j.client.audio.opus;
/** An {@link OpusEncoder} configured through libopus' own controls; a binding supplies {@link #ctl}. */ /** An {@link OpusEncoder} configured through libopus' own controls; a binding supplies {@link #ctl}. */
public abstract class CtlOpusEncoder implements OpusEncoder { public abstract class AbstractCtlOpusEncoder implements OpusEncoder {
/** Calls {@code opus_encoder_ctl(encoder, request, value)}. */ /** Calls {@code opus_encoder_ctl(encoder, request, value)}. */
protected abstract void ctl(int request, int value); protected abstract void ctl(int request, int value);
@@ -0,0 +1,30 @@
package eu.lixko.ts3j.client.chat;
/**
* One conversation on a server: its server chat, its channel chat, or the private chat with a
* client.
*
* @param clientId the peer of a private chat; 0 for the others
*/
public record ChatKey(ChatScope scope, int clientId) {
public static final ChatKey SERVER = new ChatKey(ChatScope.SERVER, 0);
public static final ChatKey CHANNEL = new ChatKey(ChatScope.CHANNEL, 0);
public static ChatKey privateWith(int clientId) {
return new ChatKey(ChatScope.PRIVATE, clientId);
}
/** The conversation a message in {@code scope} belongs to; {@code peerClientId} counts only for a private one. */
public static ChatKey of(ChatScope scope, int peerClientId) {
return switch (scope) {
case SERVER -> SERVER;
case CHANNEL -> CHANNEL;
case PRIVATE -> privateWith(peerClientId);
};
}
public boolean isPrivate() {
return scope == ChatScope.PRIVATE;
}
}
@@ -0,0 +1,8 @@
package eu.lixko.ts3j.client.chat;
/** Which chat a message is in: the server's, the channel's, or a private one with a client. */
public enum ChatScope {
SERVER,
CHANNEL,
PRIVATE
}
@@ -0,0 +1,30 @@
package eu.lixko.ts3j.client.chat;
import java.util.List;
/**
* Where a server's chat lines go, already rendered as {@link eu.lixko.ts3j.client.text.ChatHtml}
* HTML. The frontend keeps and shows them; calls arrive on connection threads.
*/
public interface ChatSink {
/**
* Adds a line to a conversation, opening a private one if it is not open.
*
* @param title the peer's name for a private chat; empty for the server and channel chats
*/
void append(ChatKey key, String title, String html);
/** Replaces a conversation's lines with what its log held, opening a private one if needed. */
void setHistory(ChatKey key, String title, List<String> html);
/**
* The server's or the channel's name, which their conversations go by.
*
* @param name blank while there is none, e.g. when not connected
*/
void rename(ChatKey key, String name);
/** Leaving the server ends its private chats. */
void closePrivateChats();
}
@@ -1,7 +0,0 @@
package eu.lixko.ts3j.client.chatlog;
public enum ChatLogScope {
SERVER,
CHANNEL,
PRIVATE
}
@@ -1,5 +1,6 @@
package eu.lixko.ts3j.client.chatlog; package eu.lixko.ts3j.client.chatlog;
import eu.lixko.ts3j.client.chat.ChatScope;
import eu.lixko.ts3j.client.config.AppDirs; import eu.lixko.ts3j.client.config.AppDirs;
import eu.lixko.ts3j.client.text.BBCode; import eu.lixko.ts3j.client.text.BBCode;
import eu.lixko.ts3j.client.text.HtmlText; import eu.lixko.ts3j.client.text.HtmlText;
@@ -59,21 +60,21 @@ public final class ChatLogStore {
public synchronized void begin() throws IOException { public synchronized void begin() throws IOException {
LocalDateTime now = LocalDateTime.now(); LocalDateTime now = LocalDateTime.now();
appendRaw(log(ChatLogScope.SERVER), "*** Log begins " + BEGIN.format(now), beginHtml("Log", now)); appendRaw(log(ChatScope.SERVER), "*** Log begins " + BEGIN.format(now), beginHtml("Log", now));
appendRaw(log(ChatLogScope.CHANNEL), "*** Chat begins " + BEGIN.format(now), beginHtml("Chat", now)); appendRaw(log(ChatScope.CHANNEL), "*** Chat begins " + BEGIN.format(now), beginHtml("Chat", now));
} }
public List<String> serverHtmlHistory() throws IOException { public List<String> serverHtmlHistory() throws IOException {
return last(readHtml(log(ChatLogScope.SERVER), HISTORY_TAIL_BYTES), HISTORY_LIMIT); return last(readHtml(log(ChatScope.SERVER), HISTORY_TAIL_BYTES), HISTORY_LIMIT);
} }
public List<String> channelHtmlHistory() throws IOException { public List<String> channelHtmlHistory() throws IOException {
return last(readTextMessages(log(ChatLogScope.CHANNEL), ChatLogScope.CHANNEL, HISTORY_TAIL_BYTES), return last(readTextMessages(log(ChatScope.CHANNEL), ChatScope.CHANNEL, HISTORY_TAIL_BYTES),
HISTORY_LIMIT); HISTORY_LIMIT);
} }
public List<String> privateHtmlHistory(String clientUniqueId) throws IOException { public List<String> privateHtmlHistory(String clientUniqueId) throws IOException {
return last(readTextMessages(privateLog(clientUniqueId), ChatLogScope.PRIVATE, HISTORY_TAIL_BYTES), return last(readTextMessages(privateLog(clientUniqueId), ChatScope.PRIVATE, HISTORY_TAIL_BYTES),
HISTORY_LIMIT); HISTORY_LIMIT);
} }
@@ -87,14 +88,14 @@ public final class ChatLogStore {
/** /**
* Searches a whole log, not only the part {@link #HISTORY_LIMIT} loads into a chat. * Searches a whole log, not only the part {@link #HISTORY_LIMIT} loads into a chat.
* *
* @param clientUniqueId the peer, for {@link ChatLogScope#PRIVATE}; ignored otherwise * @param clientUniqueId the peer, for {@link ChatScope#PRIVATE}; ignored otherwise
* @param limit how many of the newest matches to return * @param limit how many of the newest matches to return
*/ */
public SearchResult search(ChatLogScope scope, String clientUniqueId, TextQuery query, int limit) public SearchResult search(ChatScope scope, String clientUniqueId, TextQuery query, int limit)
throws IOException { throws IOException {
List<String> all = scope == ChatLogScope.SERVER List<String> all = scope == ChatScope.SERVER
? readHtml(log(scope), Long.MAX_VALUE) ? readHtml(log(scope), Long.MAX_VALUE)
: readTextMessages(scope == ChatLogScope.PRIVATE ? privateLog(clientUniqueId) : log(scope), scope, : readTextMessages(scope == ChatScope.PRIVATE ? privateLog(clientUniqueId) : log(scope), scope,
Long.MAX_VALUE); Long.MAX_VALUE);
List<String> hits = new ArrayList<>(); List<String> hits = new ArrayList<>();
for (String entry : all) { for (String entry : all) {
@@ -104,9 +105,9 @@ public final class ChatLogStore {
} }
/** Logs a message; a private one goes to the log of the client it came from. */ /** Logs a message; a private one goes to the log of the client it came from. */
public synchronized String appendMessage(ChatLogScope scope, boolean outgoing, int clientId, String uniqueId, public synchronized String appendMessage(ChatScope scope, boolean outgoing, int clientId, String uniqueId,
String nickname, String message) throws IOException { String nickname, String message) throws IOException {
LogFiles files = scope == ChatLogScope.PRIVATE ? privateLog(uniqueId) : log(scope); LogFiles files = scope == ChatScope.PRIVATE ? privateLog(uniqueId) : log(scope);
return append(files, scope, outgoing, clientId, uniqueId, nickname, message); return append(files, scope, outgoing, clientId, uniqueId, nickname, message);
} }
@@ -114,11 +115,11 @@ public final class ChatLogStore {
public synchronized String appendPrivateMessage(String peerUniqueId, boolean outgoing, int clientId, public synchronized String appendPrivateMessage(String peerUniqueId, boolean outgoing, int clientId,
String uniqueId, String nickname, String message) String uniqueId, String nickname, String message)
throws IOException { throws IOException {
return append(privateLog(peerUniqueId), ChatLogScope.PRIVATE, outgoing, clientId, uniqueId, nickname, return append(privateLog(peerUniqueId), ChatScope.PRIVATE, outgoing, clientId, uniqueId, nickname,
message); message);
} }
private String append(LogFiles files, ChatLogScope scope, boolean outgoing, int clientId, String uniqueId, private String append(LogFiles files, ChatScope scope, boolean outgoing, int clientId, String uniqueId,
String nickname, String message) throws IOException { String nickname, String message) throws IOException {
LocalDateTime now = LocalDateTime.now(); LocalDateTime now = LocalDateTime.now();
String text = "<" + TIME.format(now) + "> " + safe(nickname) + ": " + safe(message); String text = "<" + TIME.format(now) + "> " + safe(nickname) + ": " + safe(message);
@@ -131,7 +132,7 @@ public final class ChatLogStore {
LocalDateTime now = LocalDateTime.now(); LocalDateTime now = LocalDateTime.now();
String text = "<" + TIME.format(now) + "> " + safe(message); String text = "<" + TIME.format(now) + "> " + safe(message);
String html = eventHtml(now, BBCode.linksToHtml(message)); String html = eventHtml(now, BBCode.linksToHtml(message));
appendRaw(log(ChatLogScope.SERVER), text, html); appendRaw(log(ChatScope.SERVER), text, html);
return html; return html;
} }
@@ -143,7 +144,7 @@ public final class ChatLogStore {
return new String(Base64.getDecoder().decode(value), StandardCharsets.UTF_8); return new String(Base64.getDecoder().decode(value), StandardCharsets.UTF_8);
} }
private LogFiles log(ChatLogScope scope) { private LogFiles log(ChatScope scope) {
return switch (scope) { return switch (scope) {
case SERVER -> new LogFiles(serverDir.resolve("server.txt"), serverDir.resolve("server.html")); case SERVER -> new LogFiles(serverDir.resolve("server.txt"), serverDir.resolve("server.html"));
case CHANNEL -> new LogFiles(serverDir.resolve("channel.txt"), serverDir.resolve("channel.html")); case CHANNEL -> new LogFiles(serverDir.resolve("channel.txt"), serverDir.resolve("channel.html"));
@@ -197,7 +198,7 @@ public final class ChatLogStore {
* A message is written as it was sent, so one with line breaks spans several lines of the * A message is written as it was sent, so one with line breaks spans several lines of the
* log: a line that starts no entry of its own continues the message before it. * log: a line that starts no entry of its own continues the message before it.
*/ */
private static List<String> readTextMessages(LogFiles files, ChatLogScope scope, long tailBytes) private static List<String> readTextMessages(LogFiles files, ChatScope scope, long tailBytes)
throws IOException { throws IOException {
if (!Files.isRegularFile(files.txt)) return Collections.emptyList(); if (!Files.isRegularFile(files.txt)) return Collections.emptyList();
List<String> entries = new ArrayList<>(); List<String> entries = new ArrayList<>();
@@ -250,7 +251,7 @@ public final class ChatLogStore {
+ BBCode.escape(line) + "</span></div>"; + BBCode.escape(line) + "</span></div>";
} }
private static String messageLineHtml(Matcher m, CharSequence text, ChatLogScope scope) { private static String messageLineHtml(Matcher m, CharSequence text, ChatScope scope) {
String target = switch (scope) { String target = switch (scope) {
case PRIVATE -> "Private"; case PRIVATE -> "Private";
case CHANNEL -> "Channel"; case CHANNEL -> "Channel";
@@ -268,7 +269,7 @@ public final class ChatLogStore {
+ "*** " + kind + " begins " + BEGIN.format(timestamp) + "</span></p>"; + "*** " + kind + " begins " + BEGIN.format(timestamp) + "</span></p>";
} }
private static String messageHtml(ChatLogScope scope, boolean outgoing, LocalDateTime timestamp, private static String messageHtml(ChatScope scope, boolean outgoing, LocalDateTime timestamp,
int clientId, String uniqueId, String nickname, String message) { int clientId, String uniqueId, String nickname, String message) {
String target = switch (scope) { String target = switch (scope) {
case PRIVATE -> "Private"; case PRIVATE -> "Private";
@@ -24,6 +24,10 @@ public final class Bookmark {
public String channelPassword = ""; public String channelPassword = "";
/** Connect to this server automatically when the client starts. */ /** Connect to this server automatically when the client starts. */
public boolean connectOnStartup = false; public boolean connectOnStartup = false;
/** TeamSpeak's "Enable myTeamSpeak features" ({@code Bookmark_Data.send_mytsid_on_server}). */
public boolean myTeamSpeakFeatures = true;
/** Offer whispering in this server's menus. */
public boolean showWhisperControls = false;
/** The server's icon as last seen there, 0 for none or not yet known. */ /** The server's icon as last seen there, 0 for none or not yet known. */
public long iconId = 0; public long iconId = 0;
@@ -46,6 +50,8 @@ public final class Bookmark {
b.channel = channel; b.channel = channel;
b.channelPassword = channelPassword; b.channelPassword = channelPassword;
b.connectOnStartup = connectOnStartup; b.connectOnStartup = connectOnStartup;
b.myTeamSpeakFeatures = myTeamSpeakFeatures;
b.showWhisperControls = showWhisperControls;
b.iconId = iconId; b.iconId = iconId;
return b; return b;
} }
@@ -88,6 +88,8 @@ public final class Bookmarks {
bm.channel = p.getProperty(prefix + "channel", ""); bm.channel = p.getProperty(prefix + "channel", "");
bm.channelPassword = p.getProperty(prefix + "channelPassword", ""); bm.channelPassword = p.getProperty(prefix + "channelPassword", "");
bm.connectOnStartup = Boolean.parseBoolean(p.getProperty(prefix + "connectOnStartup", "false")); bm.connectOnStartup = Boolean.parseBoolean(p.getProperty(prefix + "connectOnStartup", "false"));
bm.myTeamSpeakFeatures = Boolean.parseBoolean(p.getProperty(prefix + "myTeamSpeakFeatures", "true"));
bm.showWhisperControls = Boolean.parseBoolean(p.getProperty(prefix + "showWhisperControls", "false"));
bm.iconId = parseLong(p.getProperty(prefix + "iconId")); bm.iconId = parseLong(p.getProperty(prefix + "iconId"));
if (bm.address != null && !bm.address.isBlank()) b.entries.add(bm); if (bm.address != null && !bm.address.isBlank()) b.entries.add(bm);
} }
@@ -110,6 +112,8 @@ public final class Bookmarks {
p.setProperty(prefix + "channel", nullToEmpty(bm.channel)); p.setProperty(prefix + "channel", nullToEmpty(bm.channel));
p.setProperty(prefix + "channelPassword", nullToEmpty(bm.channelPassword)); p.setProperty(prefix + "channelPassword", nullToEmpty(bm.channelPassword));
p.setProperty(prefix + "connectOnStartup", Boolean.toString(bm.connectOnStartup)); p.setProperty(prefix + "connectOnStartup", Boolean.toString(bm.connectOnStartup));
p.setProperty(prefix + "myTeamSpeakFeatures", Boolean.toString(bm.myTeamSpeakFeatures));
p.setProperty(prefix + "showWhisperControls", Boolean.toString(bm.showWhisperControls));
p.setProperty(prefix + "iconId", Long.toString(bm.iconId)); p.setProperty(prefix + "iconId", Long.toString(bm.iconId));
} }
try { try {
@@ -117,10 +117,10 @@ public final class IdentityStore {
IdentityEntry e = byId(preferredId); IdentityEntry e = byId(preferredId);
if (e != null) return e; if (e != null) return e;
e = byId(settings.defaultIdentityId); e = byId(settings.defaultIdentityId.get());
if (e == null) { if (e == null) {
e = entries.isEmpty() ? generate("Default", DEFAULT_SECURITY_LEVEL) : entries.get(0); e = entries.isEmpty() ? generate("Default", DEFAULT_SECURITY_LEVEL) : entries.get(0);
settings.defaultIdentityId = e.getId(); settings.defaultIdentityId.set(e.getId());
settings.save(); settings.save();
} }
return e; return e;
@@ -161,6 +161,23 @@ public final class IdentityStore {
return LocalIdentity.read(new ByteArrayInputStream(ini.getBytes(StandardCharsets.US_ASCII))); return LocalIdentity.read(new ByteArrayInputStream(ini.getBytes(StandardCharsets.US_ASCII)));
} }
/** The identity in the {@code <offset>V<obfuscated key>} form {@link #parseIdentityString} reads. */
public static String identityString(LocalIdentity identity) throws IOException {
Ini ini = new Ini(new ByteArrayInputStream(identity.export().getBytes(StandardCharsets.UTF_8)));
String value = unquote(ini.get("Identity", "identity"));
if (value == null) throw new IOException("Identity did not export");
return value;
}
/** Takes the key offset of another copy of the same key, raising or lowering its security level. */
public synchronized void setKeyOffset(IdentityEntry entry, LocalIdentity sameKey) throws IOException {
if (!sameKey.getUid().toBase64().equals(entry.getUniqueId())) throw new IOException("Not the same key");
entry.getIdentity().setKeyOffset(sameKey.getKeyOffset());
entry.getIdentity().setLastCheckedKeyOffset(
Math.max(entry.getIdentity().getLastCheckedKeyOffset(), sameKey.getLastCheckedKeyOffset()));
write(entry, entry.getFile());
}
/** Files an existing key pair as a managed identity under the given name. */ /** Files an existing key pair as a managed identity under the given name. */
public IdentityEntry add(String name, LocalIdentity identity, String nickname, String phoneticNickname) public IdentityEntry add(String name, LocalIdentity identity, String nickname, String phoneticNickname)
throws IOException { throws IOException {
@@ -197,8 +214,8 @@ public final class IdentityStore {
//noinspection ResultOfMethodCallIgnored //noinspection ResultOfMethodCallIgnored
entry.getFile().delete(); entry.getFile().delete();
if (entry.getId().equals(settings.defaultIdentityId)) { if (entry.getId().equals(settings.defaultIdentityId.get())) {
settings.defaultIdentityId = entries.isEmpty() ? "" : entries.get(0).getId(); settings.defaultIdentityId.set(entries.isEmpty() ? "" : entries.get(0).getId());
settings.save(); settings.save();
} }
if (bookmarks != null) { if (bookmarks != null) {
@@ -0,0 +1,78 @@
package eu.lixko.ts3j.client.config;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.UnaryOperator;
/**
* One value of {@link Settings}: its key in the settings file, how it is written there, and who
* to tell when it changes. Listeners run on the thread that sets the value.
*/
public final class Setting<T> {
private final String key;
private final Function<String, T> parse;
private final Function<T, String> format;
private final UnaryOperator<T> constrain;
private final List<Consumer<? super T>> listeners = new CopyOnWriteArrayList<>();
private volatile T value;
/**
* @param parse reads the file's text; throws {@link IllegalArgumentException} for text it
* can't read, which keeps the default
* @param constrain brings a value into range, both when read and when set
*/
Setting(String key, T initial, Function<String, T> parse, Function<T, String> format, UnaryOperator<T> constrain) {
this.key = key;
this.parse = parse;
this.format = format;
this.constrain = constrain;
this.value = initial;
}
public String key() {
return key;
}
public T get() {
return value;
}
public void set(T newValue) {
T constrained = constrain.apply(Objects.requireNonNull(newValue));
if (constrained.equals(value)) return;
value = constrained;
for (Consumer<? super T> listener : listeners) listener.accept(constrained);
}
public void addListener(Consumer<? super T> listener) {
listeners.add(listener);
}
public void removeListener(Consumer<? super T> listener) {
listeners.remove(listener);
}
/** Runs {@code action} whenever any of {@code settings} changes. */
public static void onAnyChange(Runnable action, Setting<?>... settings) {
for (Setting<?> setting : settings) setting.addListener(v -> action.run());
}
void load(Properties props) {
String text = props.getProperty(key);
if (text == null) return;
try {
value = constrain.apply(parse.apply(text));
} catch (IllegalArgumentException unreadable) {
// keeps the default
}
}
void store(Properties props) {
props.setProperty(key, format.apply(value));
}
}
@@ -1,5 +1,6 @@
package eu.lixko.ts3j.client.config; package eu.lixko.ts3j.client.config;
import eu.lixko.ts3j.client.audio.InputLevel;
import eu.lixko.ts3j.client.contacts.ContactDefaults; import eu.lixko.ts3j.client.contacts.ContactDefaults;
import eu.lixko.ts3j.client.sound.NotificationSettings; import eu.lixko.ts3j.client.sound.NotificationSettings;
@@ -7,15 +8,18 @@ import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties; import java.util.Properties;
import java.util.function.Function;
import java.util.function.UnaryOperator;
/** /**
* Simple persistent settings backed by a properties file in the user's home * Simple persistent settings backed by a properties file in the user's home
* directory (~/.ts3jclient/settings.properties). * directory (~/.ts3jclient/settings.properties).
* *
* <p>Holds connection defaults, audio device selection and voice-activation * <p>Holds connection defaults, audio device selection and voice-activation
* parameters. Loaded once at startup and saved whenever the user changes * parameters. Loaded once at startup; whoever changes a {@link Setting} saves.
* something in the options dialog.
*/ */
public final class Settings { public final class Settings {
@@ -70,138 +74,149 @@ public final class Settings {
} }
private final Properties props = new Properties(); private final Properties props = new Properties();
private final List<Setting<?>> all = new ArrayList<>();
// ---- connection ---- // ---- connection ----
public String lastAddress = "localhost"; public final Setting<String> lastAddress = text("lastAddress", "localhost");
public String nickname = System.getProperty("user.name", "TS3j User"); public final Setting<String> nickname = text("nickname", System.getProperty("user.name", "TS3j User"));
public String serverPassword = ""; public final Setting<String> serverPassword = text("serverPassword", "");
/** Legacy single-identity file; only used to migrate into the identity store. */ /** Legacy single-identity file; only used to migrate into the identity store. */
public String identityFile = AppDirs.file("identity.ini").getAbsolutePath(); public final Setting<String> identityFile = text("identityFile", AppDirs.file("identity.ini").getAbsolutePath());
/** Id of the identity used when a server doesn't select one of its own. */ /** Id of the identity used when a server doesn't select one of its own. */
public String defaultIdentityId = ""; public final Setting<String> defaultIdentityId = text("defaultIdentityId", "");
// ---- reported client version ---- // ---- reported client version ----
/** Report {@link #clientVersion}/{@link #clientPlatform} instead of the built-in ones. */ /** Report {@link #clientVersion}/{@link #clientPlatform} instead of the built-in ones. */
public boolean customVersion = false; public final Setting<Boolean> customVersion = flag("customVersion", false);
/** Version string other clients see, e.g. "3.5.6 [Build: 1603963200]". */ /** Version string other clients see, e.g. "3.5.6 [Build: 1603963200]". */
public String clientVersion = ClientVersion.DEFAULT.version(); public final Setting<String> clientVersion = text("clientVersion", ClientVersion.DEFAULT.version());
/** Operating system other clients see, e.g. "Windows". */ /** Operating system other clients see, e.g. "Windows". */
public String clientPlatform = ClientVersion.DEFAULT.platform(); public final Setting<String> clientPlatform = text("clientPlatform", ClientVersion.DEFAULT.platform());
/** TeamSpeak's signature over the version and platform; servers may verify it. */ /** TeamSpeak's signature over the version and platform; servers may verify it. */
public String clientVersionSign = ClientVersion.DEFAULT.sign(); public final Setting<String> clientVersionSign = text("clientVersionSign", ClientVersion.DEFAULT.sign());
// ---- audio devices (mixer names; empty = system default) ---- // ---- audio devices (mixer names; empty = system default) ----
public String inputDevice = ""; public final Setting<String> inputDevice = text("inputDevice", "");
public String outputDevice = ""; public final Setting<String> outputDevice = text("outputDevice", "");
// ---- voice ---- // ---- voice ----
public InputMode inputMode = InputMode.VOICE_ACTIVATION; public final Setting<InputMode> inputMode = choice("inputMode", InputMode.VOICE_ACTIVATION);
/** Voice-activation strategy used when {@link #inputMode} is VOICE_ACTIVATION. */ /** Voice-activation strategy used when {@link #inputMode} is VOICE_ACTIVATION. */
public VadMode vadMode = VadMode.HYBRID; public final Setting<VadMode> vadMode = choice("vadMode", VadMode.HYBRID);
/** /**
* Volume-gate threshold on {@link eu.lixko.ts3j.client.audio.InputLevel}'s scale, the same one * Volume-gate threshold on {@link InputLevel}'s scale, the same one
* the TS3 client's slider uses: -50 (most sensitive) .. +50, defaulting to -40. * the TS3 client's slider uses: -50 (most sensitive) .. +50, defaulting to -40.
*/ */
public double vadThresholdDb = -40.0; public final Setting<Double> vadThresholdDb = decimal("vadLevelDb", -40.0);
/** /**
* Speech-probability threshold (0..1) for Automatic/Hybrid modes. TS3 calls this * Speech-probability threshold (0..1) for Automatic/Hybrid modes. TS3 calls this
* {@code vad_likelihood} and also defaults it to 0.5. * {@code vad_likelihood} and also defaults it to 0.5.
*/ */
public double speechThreshold = 0.5; public final Setting<Double> speechThreshold = decimal("speechThreshold", 0.5);
/** Keep voice activation running while in push-to-talk mode. */ /** Keep voice activation running while in push-to-talk mode. */
public boolean vadOverPtt = false; public final Setting<Boolean> vadOverPtt = flag("vadOverPtt", false);
/** Opus target bitrate in bits/sec. */ /** Opus target bitrate in bits/sec. */
public int bitrate = 48000; public final Setting<Integer> bitrate = number("bitrate", 48000);
/** Opus complexity 0..10. */ /** Opus complexity 0..10. */
public int complexity = 10; public final Setting<Integer> complexity = number("complexity", 10);
/** Opus variable bitrate. */ /** Opus variable bitrate. */
public boolean vbr = true; public final Setting<Boolean> vbr = flag("vbr", true);
/** Opus in-band forward error correction. */ /** Opus in-band forward error correction. */
public boolean fec = true; public final Setting<Boolean> fec = flag("fec", true);
/** Expected packet loss percent (drives FEC). */ /** Expected packet loss percent (drives FEC). */
public int packetLoss = 5; public final Setting<Integer> packetLoss = number("packetLoss", 5);
/** Encode as music (OPUS_MUSIC) rather than voice (OPUS_VOICE). */ /** Encode as music (OPUS_MUSIC) rather than voice (OPUS_VOICE). */
public boolean music = false; public final Setting<Boolean> music = flag("music", false);
/** /**
* Milliseconds between a voice packet and each of its {@link #redundancyCopies}, 0 for off. * Milliseconds between a voice packet and each of its {@link #redundancyCopies}, 0 for off.
* Listeners' jitter buffers grow to wait for the last copy, so it buys loss resilience with * Listeners' jitter buffers grow to wait for the last copy, so it buys loss resilience with
* about {@code redundancyDelay * redundancyCopies} of latency. * about {@code redundancyDelay * redundancyCopies} of latency.
*/ */
public int redundancyDelay = 0; public final Setting<Integer> redundancyDelay = number("redundancyDelay", 0);
/** The {@link #redundancyDelay} choices the settings offer; whole 20 ms voice frames. */ /** The {@link #redundancyDelay} choices the settings offer; whole 20 ms voice frames. */
public static final int[] REDUNDANCY_DELAYS = {0, 20, 40, 60, 80, 120, 200}; public static final int[] REDUNDANCY_DELAYS = {0, 20, 40, 60, 80, 120, 200};
/** How many times every voice packet is sent again. */ /** How many times every voice packet is sent again. */
public int redundancyCopies = 1; public final Setting<Integer> redundancyCopies = number("redundancyCopies", 1);
public static final int MAX_REDUNDANCY_COPIES = 4; public static final int MAX_REDUNDANCY_COPIES = 4;
/** /**
* Milliseconds of playback delay held on top of what the jitter buffer measures it needs, * Milliseconds of playback delay held on top of what the jitter buffer measures it needs,
* so late packets and error correction copies still make it on a bad connection. * so late packets and error correction copies still make it on a bad connection.
*/ */
public int receiveBuffer = 0; public final Setting<Integer> receiveBuffer = number("receiveBuffer", 0);
/** The {@link #receiveBuffer} choices the settings offer; whole 20 ms voice frames. */ /** The {@link #receiveBuffer} choices the settings offer; whole 20 ms voice frames. */
public static final int[] RECEIVE_BUFFERS = {0, 20, 40, 60, 80, 120, 200, 300, 500}; public static final int[] RECEIVE_BUFFERS = {0, 20, 40, 60, 80, 120, 200, 300, 500};
/** Master playback gain, 0..1 (may exceed 1 for boost up to 2). */ /** Master playback gain, 0..1 (may exceed 1 for boost up to 2). */
public double outputVolume = 1.0; public final Setting<Double> outputVolume = decimal("outputVolume", 1.0);
/** /**
* Global multiplier on top of {@link #outputVolume} and {@link #soundVolume}, * Global multiplier on top of {@link #outputVolume} and {@link #soundVolume},
* controlled from the toolbar's Master Volume slider so both can be ridden * controlled from the toolbar's Master Volume slider so both can be ridden
* with one control. 0..2, same boost headroom as the other volumes. * with one control. 0..2, same boost headroom as the other volumes.
*/ */
public double masterVolume = 1.0; public final Setting<Double> masterVolume = decimal("masterVolume", 1.0);
/** Microphone input gain multiplier applied before VAD/encode. */ /** Microphone input gain multiplier applied before VAD/encode. */
public double inputVolume = 1.0; public final Setting<Double> inputVolume = decimal("inputVolume", 1.0);
/** Remove steady background noise from the microphone (WebRTC noise suppression). */ /** Remove steady background noise from the microphone (WebRTC noise suppression). */
public boolean denoise = true; public final Setting<Boolean> denoise = flag("denoise", true);
/** TS3's {@code denoiser_level}: 0..3 for 6, 12, 18 or 21 dB of suppression. */ /** TS3's {@code denoiser_level}: 0..3 for 6, 12, 18 or 21 dB of suppression. */
public int denoiserLevel = 1; public final Setting<Integer> denoiserLevel = number("denoiserLevel", 1);
/** Attenuate keyboard clicks while typing. */ /** Attenuate keyboard clicks while typing. */
public boolean typingAttenuation = true; public final Setting<Boolean> typingAttenuation = flag("typingAttenuation", true);
/** Automatic gain control: normalise microphone loudness to a target level. */ /** Automatic gain control: normalise microphone loudness to a target level. */
public boolean agc = true; public final Setting<Boolean> agc = flag("agc", true);
public static final int MAX_AGC_BOOST_DB = 20; public static final int MAX_AGC_BOOST_DB = 20;
/** How many dB louder AGC may make the background noise to bring up a quiet or distant voice. */ /** How many dB louder AGC may make the background noise to bring up a quiet or distant voice. */
public int agcBoostDb = 0; public final Setting<Integer> agcBoostDb = number("agcBoostDb", 0, 0, MAX_AGC_BOOST_DB);
/** Beep when speech is picked up while the microphone is muted. */ /** Beep when speech is picked up while the microphone is muted. */
public boolean mutedTalkWarning = true; public final Setting<Boolean> mutedTalkWarning = flag("mutedTalkWarning", true);
// ---- notification sounds ---- // ---- notification sounds ----
/** Directory name of the active sound pack; empty picks the first one found. */ /** Directory name of the active sound pack; empty picks the first one found. */
public String soundPack = "default"; public final Setting<String> soundPack = text("soundPack", "default");
/** Notification sound volume, 0..1. */ /** Notification sound volume, 0..1. */
public double soundVolume = 1.0; public final Setting<Double> soundVolume = decimal("soundVolume", 1.0);
/** Extra folder to look for sound packs in, on top of the well-known locations. */ /** Extra folder to look for sound packs in, on top of the well-known locations. */
public String soundPackDir = ""; public final Setting<String> soundPackDir = text("soundPackDir", "");
/** Whether pokes and private messages show a desktop notification while the window is in the background. */ /** Whether pokes and private messages show a desktop notification while the window is in the background. */
public boolean desktopNotifications = true; public final Setting<Boolean> desktopNotifications = flag("desktopNotifications", true);
// ---- icons ---- // ---- icons ----
/** File name of the active icon pack; empty uses the built-in icons. */ /** File name of the active icon pack; empty uses the built-in icons. */
public String iconPack = "default_colored_2014.zip"; public final Setting<String> iconPack = text("iconPack", "default_colored_2014.zip");
/** /**
* Whether the channel tree shows each client's country flag, as TeamSpeak's EnableCountryFlags; * Whether the channel tree shows each client's country flag, as TeamSpeak's EnableCountryFlags;
* their details show it beside their name either way. * their details show it beside their name either way.
*/ */
public boolean countryFlags = false; public final Setting<Boolean> countryFlags = flag("countryFlags", false);
/** Background colours of client rows in the channel tree. */ /** Background colours of client rows in the channel tree. */
public final ClientRowColors clientRowColors = new ClientRowColors(); public final ClientRowColors clientRowColors = new ClientRowColors();
/** Extra folder to look for icon packs in, on top of the well-known locations. */ /** Extra folder to look for icon packs in, on top of the well-known locations. */
public String iconPackDir = ""; public final Setting<String> iconPackDir = text("iconPackDir", "");
/** Look-and-feel variant; see {@link Appearance}. */ /** Look-and-feel variant; see {@link Appearance}. */
public Appearance appearance = Appearance.LIGHT; public final Setting<Appearance> appearance = choice("appearance", Appearance.LIGHT);
/** Interface scale factor, 1.0 being 100&nbsp;%; 0 follows the desktop. Read at startup. */ /** Interface scale factor, 1.0 being 100&nbsp;%; 0 follows the desktop. Read at startup. */
public double uiScale = 0; public final Setting<Double> uiScale = decimal("uiScale", 0);
// ---- window chrome ---- // ---- window chrome ----
/** Whether the status bar at the bottom of the window is shown. */ /** Whether the status bar at the bottom of the window is shown. */
public boolean showStatusBar = true; public final Setting<Boolean> showStatusBar = flag("showStatusBar", true);
/** The main toolbar's buttons in order, comma-separated action ids with "-" for a separator; empty for the default set. */
public final Setting<String> toolbarLayout = text("toolbarLayout", "");
/** Whether the Master Volume slider is shown on the toolbar. */ /** Whether the Master Volume slider is shown on the toolbar. */
public boolean showMasterVolumeSlider = true; public final Setting<Boolean> showMasterVolumeSlider = flag("showMasterVolumeSlider", true);
/** Share of the tree/info column the tree takes, i.e. where their divider sits. */ /** Share of the tree/info column the tree takes, i.e. where their divider sits. */
public double infoSplitRatio = 0.68; public final Setting<Double> infoSplitRatio = decimal("infoSplitRatio", 0.68);
/** Share of the window's width the tree/info column takes, beside the chat. */
public final Setting<Double> chatSplitRatio = decimal("chatSplitRatio", 0.45);
/** The main window's bounds when not maximised; a width of 0 until it has been placed. */
public final Setting<Integer> windowX = number("windowX", 0);
public final Setting<Integer> windowY = number("windowY", 0);
public final Setting<Integer> windowWidth = number("windowWidth", 0);
public final Setting<Integer> windowHeight = number("windowHeight", 0);
public final Setting<Boolean> windowMaximized = flag("windowMaximized", false);
/** Whether the ban list shows the bans we created ourselves in bold. */ /** Whether the ban list shows the bans we created ourselves in bold. */
public boolean banHighlightOwn = true; public final Setting<Boolean> banHighlightOwn = flag("banHighlightOwn", true);
/** The ban list columns the user shows, comma-separated column names; empty for the default set. */ /** The ban list columns the user shows, comma-separated column names; empty for the default set. */
public String banListColumns = ""; public final Setting<String> banListColumns = text("banListColumns", "");
/** What the Server Log window shows and how. */ /** What the Server Log window shows and how. */
public final ServerLogSettings serverLog = new ServerLogSettings(); public final ServerLogSettings serverLog = new ServerLogSettings();
@@ -213,22 +228,22 @@ public final class Settings {
/** What a client starts out with when added to the contacts as a friend, blocked or neutral. */ /** What a client starts out with when added to the contacts as a friend, blocked or neutral. */
public final ContactDefaults contactDefaults = new ContactDefaults(); public final ContactDefaults contactDefaults = new ContactDefaults();
/** Colour friends and blocked clients in the server tree, as the TeamSpeak client does. */ /** Colour friends and blocked clients in the server tree, as the TeamSpeak client does. */
public boolean colorContacts = true; public final Setting<Boolean> colorContacts = flag("colorContacts", true);
/** Whose whispers are played. */ /** Whose whispers are played. */
public WhisperPolicy whisperPolicy = WhisperPolicy.ALLOW_UNLESS_DENIED; public final Setting<WhisperPolicy> whisperPolicy = choice("whisperPolicy", WhisperPolicy.ALLOW_UNLESS_DENIED);
/** Keep chat logs, and show their history when a chat opens. */ /** Keep chat logs, and show their history when a chat opens. */
public boolean chatLogs = true; public final Setting<Boolean> chatLogs = flag("chatLogs", true);
/** Where chat logs go; empty for the TeamSpeak 3 client's own folder, so both share them. */ /** Where chat logs go; empty for the TeamSpeak 3 client's own folder, so both share them. */
public String chatLogDir = ""; public final Setting<String> chatLogDir = text("chatLogDir", "");
/** The folder recordings were last saved to; empty for {@code ~/Recordings}. */ /** The folder recordings were last saved to; empty for {@code ~/Recordings}. */
public String recordingDir = ""; public final Setting<String> recordingDir = text("recordingDir", "");
/** Whether descriptions show their pictures, fetched from the web, or only links to them. */ /** Whether descriptions show their pictures, fetched from the web, or only links to them. */
public boolean descriptionPictures = true; public final Setting<Boolean> descriptionPictures = flag("descriptionPictures", true);
/** Ctrl+wheel zoom of the chat's text and pictures, 1.0 being 100&nbsp;%. */ /** Ctrl+wheel zoom of the chat's text and pictures, 1.0 being 100&nbsp;%. */
public double chatZoom = 1.0; public final Setting<Double> chatZoom = decimal("chatZoom", 1.0);
/** Ctrl+wheel zoom of the info panel's text and pictures, 1.0 being 100&nbsp;%. */ /** Ctrl+wheel zoom of the info panel's text and pictures, 1.0 being 100&nbsp;%. */
public double infoZoom = 1.0; public final Setting<Double> infoZoom = decimal("infoZoom", 1.0);
public static Settings load() { public static Settings load() {
Settings s = new Settings(); Settings s = new Settings();
@@ -237,7 +252,12 @@ public final class Settings {
try (FileInputStream in = new FileInputStream(file())) { try (FileInputStream in = new FileInputStream(file())) {
s.props.load(in); s.props.load(in);
} }
s.applyFromProps(); s.migrateThreshold();
for (Setting<?> setting : s.all) setting.load(s.props);
s.clientRowColors.load(s.props);
s.notifications.load(s.props);
s.serverLog.load(s.props);
s.contactDefaults.load(s.props);
} }
} catch (Exception ignored) { } catch (Exception ignored) {
// Corrupt/unreadable settings -> fall back to defaults. // Corrupt/unreadable settings -> fall back to defaults.
@@ -248,198 +268,81 @@ public final class Settings {
public void save() { public void save() {
try { try {
AppDirs.createProfile(); AppDirs.createProfile();
writeToProps(); for (Setting<?> setting : all) setting.store(props);
clientRowColors.store(props);
notifications.store(props);
serverLog.store(props);
contactDefaults.store(props);
ProfileFiles.write(file(), out -> props.store(out, "TeamSpook TS3j settings")); ProfileFiles.write(file(), out -> props.store(out, "TeamSpook TS3j settings"));
} catch (Exception ignored) { } catch (Exception ignored) {
} }
} }
public File identityFile() { public File identityFile() {
return new File(identityFile); return new File(identityFile.get());
} }
public Path recordingFolder() { public Path recordingFolder() {
return recordingDir.isBlank() return recordingDir.get().isBlank()
? Paths.get(System.getProperty("user.home", "."), "Recordings") ? Paths.get(System.getProperty("user.home", "."), "Recordings")
: Paths.get(recordingDir); : Paths.get(recordingDir.get());
} }
/** {@link #outputVolume} scaled by the Master Volume slider. */ /** {@link #outputVolume} scaled by the Master Volume slider. */
public double effectiveOutputVolume() { public double effectiveOutputVolume() {
return outputVolume * masterVolume; return outputVolume.get() * masterVolume.get();
} }
/** {@link #soundVolume} scaled by the Master Volume slider. */ /** {@link #soundVolume} scaled by the Master Volume slider. */
public double effectiveSoundVolume() { public double effectiveSoundVolume() {
return soundVolume * masterVolume; return soundVolume.get() * masterVolume.get();
} }
private void applyFromProps() { private <T> Setting<T> add(String key, T initial, Function<String, T> parse, Function<T, String> format,
lastAddress = props.getProperty("lastAddress", lastAddress); UnaryOperator<T> constrain) {
nickname = props.getProperty("nickname", nickname); Setting<T> setting = new Setting<>(key, initial, parse, format, constrain);
serverPassword = props.getProperty("serverPassword", serverPassword); all.add(setting);
identityFile = props.getProperty("identityFile", identityFile); return setting;
defaultIdentityId = props.getProperty("defaultIdentityId", defaultIdentityId);
customVersion = parseB(props.getProperty("customVersion"), customVersion);
clientVersion = props.getProperty("clientVersion", clientVersion);
clientPlatform = props.getProperty("clientPlatform", clientPlatform);
clientVersionSign = props.getProperty("clientVersionSign", clientVersionSign);
inputDevice = props.getProperty("inputDevice", inputDevice);
outputDevice = props.getProperty("outputDevice", outputDevice);
inputMode = parseEnum(InputMode.class, props.getProperty("inputMode"), inputMode);
vadMode = parseEnum(VadMode.class, props.getProperty("vadMode"), vadMode);
vadThresholdDb = parseD(props.getProperty("vadLevelDb"),
migrateThreshold(props.getProperty("vadThresholdDb"), vadThresholdDb));
speechThreshold = parseD(props.getProperty("speechThreshold"), speechThreshold);
vadOverPtt = parseB(props.getProperty("vadOverPtt"), vadOverPtt);
bitrate = parseI(props.getProperty("bitrate"), bitrate);
complexity = parseI(props.getProperty("complexity"), complexity);
vbr = parseB(props.getProperty("vbr"), vbr);
fec = parseB(props.getProperty("fec"), fec);
packetLoss = parseI(props.getProperty("packetLoss"), packetLoss);
music = parseB(props.getProperty("music"), music);
redundancyDelay = parseI(props.getProperty("redundancyDelay"), redundancyDelay);
redundancyCopies = parseI(props.getProperty("redundancyCopies"), redundancyCopies);
receiveBuffer = parseI(props.getProperty("receiveBuffer"), receiveBuffer);
outputVolume = parseD(props.getProperty("outputVolume"), outputVolume);
masterVolume = parseD(props.getProperty("masterVolume"), masterVolume);
inputVolume = parseD(props.getProperty("inputVolume"), inputVolume);
denoise = parseB(props.getProperty("denoise"), denoise);
denoiserLevel = parseI(props.getProperty("denoiserLevel"), denoiserLevel);
typingAttenuation = parseB(props.getProperty("typingAttenuation"), typingAttenuation);
mutedTalkWarning = parseB(props.getProperty("mutedTalkWarning"), mutedTalkWarning);
agc = parseB(props.getProperty("agc"), agc);
agcBoostDb = Math.max(0, Math.min(MAX_AGC_BOOST_DB, parseI(props.getProperty("agcBoostDb"), agcBoostDb)));
soundPack = props.getProperty("soundPack", soundPack);
soundVolume = parseD(props.getProperty("soundVolume"), soundVolume);
soundPackDir = props.getProperty("soundPackDir", soundPackDir);
desktopNotifications = parseB(props.getProperty("desktopNotifications"), desktopNotifications);
iconPack = props.getProperty("iconPack", iconPack);
countryFlags = parseB(props.getProperty("countryFlags"), countryFlags);
clientRowColors.load(props);
iconPackDir = props.getProperty("iconPackDir", iconPackDir);
appearance = parseEnum(Appearance.class, props.getProperty("appearance"), appearance);
uiScale = parseD(props.getProperty("uiScale"), uiScale);
showStatusBar = parseB(props.getProperty("showStatusBar"), showStatusBar);
showMasterVolumeSlider = parseB(props.getProperty("showMasterVolumeSlider"), showMasterVolumeSlider);
infoSplitRatio = parseD(props.getProperty("infoSplitRatio"), infoSplitRatio);
banHighlightOwn = parseB(props.getProperty("banHighlightOwn"), banHighlightOwn);
banListColumns = props.getProperty("banListColumns", banListColumns);
notifications.load(props);
serverLog.load(props);
contactDefaults.load(props);
colorContacts = parseB(props.getProperty("colorContacts"), colorContacts);
descriptionPictures = parseB(props.getProperty("descriptionPictures"), descriptionPictures);
whisperPolicy = parseEnum(WhisperPolicy.class, props.getProperty("whisperPolicy"), whisperPolicy);
chatLogs = parseB(props.getProperty("chatLogs"), chatLogs);
chatLogDir = props.getProperty("chatLogDir", chatLogDir);
recordingDir = props.getProperty("recordingDir", recordingDir);
} }
private void writeToProps() { private Setting<String> text(String key, String initial) {
props.setProperty("lastAddress", lastAddress); return add(key, initial, Function.identity(), Function.identity(), UnaryOperator.identity());
props.setProperty("nickname", nickname);
props.setProperty("serverPassword", serverPassword);
props.setProperty("identityFile", identityFile);
props.setProperty("defaultIdentityId", defaultIdentityId);
props.setProperty("customVersion", Boolean.toString(customVersion));
props.setProperty("clientVersion", clientVersion);
props.setProperty("clientPlatform", clientPlatform);
props.setProperty("clientVersionSign", clientVersionSign);
props.setProperty("inputDevice", inputDevice);
props.setProperty("outputDevice", outputDevice);
props.setProperty("inputMode", inputMode.name());
props.setProperty("vadMode", vadMode.name());
props.setProperty("vadLevelDb", Double.toString(vadThresholdDb));
props.remove("vadThresholdDb");
props.setProperty("speechThreshold", Double.toString(speechThreshold));
props.setProperty("vadOverPtt", Boolean.toString(vadOverPtt));
props.setProperty("bitrate", Integer.toString(bitrate));
props.setProperty("complexity", Integer.toString(complexity));
props.setProperty("vbr", Boolean.toString(vbr));
props.setProperty("fec", Boolean.toString(fec));
props.setProperty("packetLoss", Integer.toString(packetLoss));
props.setProperty("music", Boolean.toString(music));
props.setProperty("redundancyDelay", Integer.toString(redundancyDelay));
props.setProperty("redundancyCopies", Integer.toString(redundancyCopies));
props.setProperty("receiveBuffer", Integer.toString(receiveBuffer));
props.setProperty("outputVolume", Double.toString(outputVolume));
props.setProperty("masterVolume", Double.toString(masterVolume));
props.setProperty("inputVolume", Double.toString(inputVolume));
props.setProperty("denoise", Boolean.toString(denoise));
props.setProperty("denoiserLevel", Integer.toString(denoiserLevel));
props.setProperty("typingAttenuation", Boolean.toString(typingAttenuation));
props.setProperty("mutedTalkWarning", Boolean.toString(mutedTalkWarning));
props.setProperty("agc", Boolean.toString(agc));
props.setProperty("agcBoostDb", Integer.toString(agcBoostDb));
props.setProperty("soundPack", soundPack);
props.setProperty("soundVolume", Double.toString(soundVolume));
props.setProperty("soundPackDir", soundPackDir);
props.setProperty("desktopNotifications", Boolean.toString(desktopNotifications));
props.setProperty("iconPack", iconPack);
props.setProperty("countryFlags", Boolean.toString(countryFlags));
clientRowColors.store(props);
props.setProperty("iconPackDir", iconPackDir);
props.setProperty("appearance", appearance.name());
props.setProperty("uiScale", Double.toString(uiScale));
props.setProperty("showStatusBar", Boolean.toString(showStatusBar));
props.setProperty("showMasterVolumeSlider", Boolean.toString(showMasterVolumeSlider));
props.setProperty("infoSplitRatio", Double.toString(infoSplitRatio));
props.setProperty("banHighlightOwn", Boolean.toString(banHighlightOwn));
props.setProperty("banListColumns", banListColumns);
notifications.store(props);
serverLog.store(props);
contactDefaults.store(props);
props.setProperty("colorContacts", Boolean.toString(colorContacts));
props.setProperty("descriptionPictures", Boolean.toString(descriptionPictures));
props.setProperty("whisperPolicy", whisperPolicy.name());
props.setProperty("chatLogs", Boolean.toString(chatLogs));
props.setProperty("chatLogDir", chatLogDir);
props.setProperty("recordingDir", recordingDir);
} }
private static <E extends Enum<E>> E parseEnum(Class<E> type, String v, E def) { private Setting<Boolean> flag(String key, boolean initial) {
if (v == null) return def; return add(key, initial, Boolean::parseBoolean, String::valueOf, UnaryOperator.identity());
try {
return Enum.valueOf(type, v.trim());
} catch (IllegalArgumentException e) {
return def;
} }
private Setting<Integer> number(String key, int initial) {
return add(key, initial, Integer::parseInt, String::valueOf, UnaryOperator.identity());
}
private Setting<Integer> number(String key, int initial, int min, int max) {
return add(key, initial, Integer::parseInt, String::valueOf, v -> Math.max(min, Math.min(max, v)));
}
private Setting<Double> decimal(String key, double initial) {
return add(key, initial, Double::parseDouble, String::valueOf, UnaryOperator.identity());
}
private <E extends Enum<E>> Setting<E> choice(String key, E initial) {
return add(key, initial, v -> Enum.valueOf(initial.getDeclaringClass(), v.trim()), Enum::name,
UnaryOperator.identity());
} }
/** /**
* Converts a threshold saved under the old {@code vadThresholdDb} key, which was in * Converts a threshold saved under the old {@code vadThresholdDb} key, which was in
* dBFS ({@code 20*log10(rms)}), to {@link eu.lixko.ts3j.client.audio.InputLevel}'s scale, so * dBFS ({@code 20*log10(rms)}), to {@link InputLevel}'s scale, so upgrading doesn't silently
* upgrading doesn't silently change how sensitive the gate is. * change how sensitive the gate is.
*/ */
private static double migrateThreshold(String legacy, double def) { private void migrateThreshold() {
double dbfs = parseD(legacy, Double.NaN); String legacy = (String) props.remove("vadThresholdDb");
if (Double.isNaN(dbfs)) { if (legacy == null || props.containsKey(vadThresholdDb.key())) return;
return def;
}
double converted = eu.lixko.ts3j.client.audio.InputLevel.powerToDb(Math.pow(10.0, dbfs / 10.0));
return Math.min(eu.lixko.ts3j.client.audio.InputLevel.MAX_DB, converted);
}
private static double parseD(String v, double def) {
if (v == null) return def;
try { try {
return Double.parseDouble(v); double converted = InputLevel.powerToDb(Math.pow(10.0, Double.parseDouble(legacy) / 10.0));
} catch (NumberFormatException e) { props.setProperty(vadThresholdDb.key(), Double.toString(Math.min(InputLevel.MAX_DB, converted)));
return def; } catch (NumberFormatException ignored) {
// keeps the default
} }
} }
private static int parseI(String v, int def) {
if (v == null) return def;
try {
return Integer.parseInt(v);
} catch (NumberFormatException e) {
return def;
}
}
private static boolean parseB(String v, boolean def) {
return v == null ? def : Boolean.parseBoolean(v);
}
} }
@@ -8,19 +8,27 @@ import java.util.Locale;
import java.util.Map; import java.util.Map;
/** /**
* One entry of the contact list, keyed by the client's unique id. * One entry of the contact list, keyed by the client's unique id — or, for a contact
* brought over from TeamSpeak 6, by a myTeamSpeak ID, which is the person rather
* than one of their identities.
* *
* <p>The fields are exactly the ones the TeamSpeak 3 client keeps for a contact, * <p>The fields are exactly the ones the TeamSpeak 3 client keeps for a contact,
* and {@link #toRecord()} / {@link #parseRecord} use its own {@code Key=Value} * and {@link #toRecord()} / {@link #parseRecord} use its own {@code Key=Value}
* serialisation (the {@code value} column of its {@code Contacts} table), so * serialisation (the {@code value} column of its {@code Contacts} table), so
* records can be exchanged with it as they are. * records can be exchanged with it as they are. The myTeamSpeak ID is an extra
* {@code MyTsId} line, written only when set.
*/ */
public final class Contact { public final class Contact {
/** TeamSpeak writes {@code LastSeen} as an ISO local date-time without zone. */ /** TeamSpeak writes {@code LastSeen} as an ISO local date-time without zone. */
private static final DateTimeFormatter LAST_SEEN = DateTimeFormatter.ISO_LOCAL_DATE_TIME; private static final DateTimeFormatter LAST_SEEN = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
/** Base64 never holds a colon, so these keys cannot pass for a unique id. */
private static final String MYTS_KEY_PREFIX = "myts:";
/** Empty for a contact known only by its {@link #myTeamSpeakId}. */
public final String uniqueId; public final String uniqueId;
/** The {@code client_myteamspeak_id} the contact's clients carry, or empty. */
public final String myTeamSpeakId;
/** Custom name; TeamSpeak seeds it with the nickname the client had when added. */ /** Custom name; TeamSpeak seeds it with the nickname the client had when added. */
public String nickname = ""; public String nickname = "";
public String phoneticNickname = ""; public String phoneticNickname = "";
@@ -42,7 +50,27 @@ public final class Contact {
public String lastSeenServerAddress = ""; public String lastSeenServerAddress = "";
public Contact(String uniqueId) { public Contact(String uniqueId) {
this(uniqueId, "");
}
public Contact(String uniqueId, String myTeamSpeakId) {
this.uniqueId = uniqueId == null ? "" : uniqueId; this.uniqueId = uniqueId == null ? "" : uniqueId;
this.myTeamSpeakId = myTeamSpeakId == null ? "" : myTeamSpeakId;
}
/** What the contact list files the entry under: the unique id, else the myTeamSpeak ID. */
public String key() {
return uniqueId.isEmpty() ? MYTS_KEY_PREFIX + myTeamSpeakId : uniqueId;
}
/** The id shown for the contact: its unique id, else its myTeamSpeak ID. */
public String shownId() {
return uniqueId.isEmpty() ? myTeamSpeakId : uniqueId;
}
/** What the contact list calls the contact: its custom name, else its id. */
public String label() {
return nickname.isBlank() ? shownId() : nickname;
} }
/** The name the contact is shown under, given the nickname it currently carries. */ /** The name the contact is shown under, given the nickname it currently carries. */
@@ -56,12 +84,12 @@ public final class Contact {
} }
public Contact copy() { public Contact copy() {
Contact c = new Contact(uniqueId); Contact c = new Contact(uniqueId, myTeamSpeakId);
c.copyFrom(this); c.copyFrom(this);
return c; return c;
} }
/** Takes over every field but the unique id. */ /** Takes over every field but the ids. */
public void copyFrom(Contact other) { public void copyFrom(Contact other) {
nickname = other.nickname; nickname = other.nickname;
phoneticNickname = other.phoneticNickname; phoneticNickname = other.phoneticNickname;
@@ -115,10 +143,11 @@ public final class Contact {
line(sb, "LastSeen", lastSeen == null ? "" : LAST_SEEN.format(lastSeen)); line(sb, "LastSeen", lastSeen == null ? "" : LAST_SEEN.format(lastSeen));
line(sb, "LastSeenServerName", lastSeenServerName); line(sb, "LastSeenServerName", lastSeenServerName);
line(sb, "LastSeenServerAddress", lastSeenServerAddress); line(sb, "LastSeenServerAddress", lastSeenServerAddress);
if (!myTeamSpeakId.isEmpty()) line(sb, "MyTsId", myTeamSpeakId);
return sb.toString(); return sb.toString();
} }
/** Parses a TeamSpeak contact record, or returns {@code null} when it carries no unique id. */ /** Parses a TeamSpeak contact record, or returns {@code null} when it carries no id at all. */
public static Contact parseRecord(String record) { public static Contact parseRecord(String record) {
if (record == null) return null; if (record == null) return null;
Map<String, String> fields = new LinkedHashMap<>(); Map<String, String> fields = new LinkedHashMap<>();
@@ -127,9 +156,10 @@ public final class Contact {
if (eq > 0) fields.put(line.substring(0, eq).trim(), line.substring(eq + 1)); if (eq > 0) fields.put(line.substring(0, eq).trim(), line.substring(eq + 1));
} }
String uid = fields.getOrDefault("IDS", "").trim(); String uid = fields.getOrDefault("IDS", "").trim();
if (uid.isEmpty()) return null; String myTsId = fields.getOrDefault("MyTsId", "").trim();
if (uid.isEmpty() && myTsId.isEmpty()) return null;
Contact c = new Contact(uid); Contact c = new Contact(uid, myTsId);
c.nickname = fields.getOrDefault("Nickname", ""); c.nickname = fields.getOrDefault("Nickname", "");
c.type = ContactType.fromCode(parseInt(fields.get("Friend"), ContactType.NEUTRAL.code())); c.type = ContactType.fromCode(parseInt(fields.get("Friend"), ContactType.NEUTRAL.code()));
c.automute = parseFlag(fields.get("Automute")); c.automute = parseFlag(fields.get("Automute"));
@@ -15,6 +15,7 @@ import java.util.Collection;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
@@ -31,6 +32,10 @@ import java.util.concurrent.atomic.AtomicBoolean;
* between the two verbatim. On first run the list is seeded from an installed * between the two verbatim. On first run the list is seeded from an installed
* TeamSpeak client's database, when one is found. * TeamSpeak client's database, when one is found.
* *
* <p>A contact known by its myTeamSpeak ID alone stands for every client carrying
* that ID, once the connection {@linkplain #link links} the client to it; lookups by
* unique id then find it like any other.
*
* <p>Safe to use from any thread: lookups are lock-free on a snapshot, and * <p>Safe to use from any thread: lookups are lock-free on a snapshot, and
* mutations are serialised and announced to listeners on the calling thread. * mutations are serialised and announced to listeners on the calling thread.
*/ */
@@ -49,7 +54,9 @@ public final class ContactStore {
} }
private final File file; private final File file;
private final Map<String, Contact> byUid = new LinkedHashMap<>(); private final Map<String, Contact> byKey = new LinkedHashMap<>();
/** Unique id → myTeamSpeak ID of the clients seen so far, which only lives as long as the client. */
private final Map<String, String> myTsIds = new ConcurrentHashMap<>();
/** Immutable snapshot for readers, replaced under the lock after every change. */ /** Immutable snapshot for readers, replaced under the lock after every change. */
private volatile List<Contact> snapshot = List.of(); private volatile List<Contact> snapshot = List.of();
private final List<Listener> listeners = new CopyOnWriteArrayList<>(); private final List<Listener> listeners = new CopyOnWriteArrayList<>();
@@ -96,9 +103,9 @@ public final class ContactStore {
if (c != null) parsed.add(c); if (c != null) parsed.add(c);
} }
synchronized (this) { synchronized (this) {
byUid.clear(); byKey.clear();
for (Contact c : parsed) byUid.put(c.uniqueId, c); for (Contact c : parsed) byKey.put(c.key(), c);
snapshot = List.copyOf(byUid.values()); snapshot = List.copyOf(byKey.values());
} }
} }
@@ -132,14 +139,33 @@ public final class ContactStore {
return snapshot; return snapshot;
} }
/**
* The contact a client is filed under: by its unique id, else by the myTeamSpeak ID it was
* {@linkplain #link linked} with. A {@link Contact#key()} finds its contact too.
*/
public Contact find(String uniqueId) { public Contact find(String uniqueId) {
if (uniqueId == null || uniqueId.isEmpty()) return null; if (uniqueId == null || uniqueId.isEmpty()) return null;
for (Contact c : snapshot) { for (Contact c : snapshot) {
if (c.uniqueId.equals(uniqueId)) return c; if (c.uniqueId.equals(uniqueId) || c.key().equals(uniqueId)) return c;
}
return findByMyTeamSpeakId(myTsIds.get(uniqueId));
}
public Contact findByMyTeamSpeakId(String myTeamSpeakId) {
if (myTeamSpeakId == null || myTeamSpeakId.isEmpty()) return null;
for (Contact c : snapshot) {
if (c.myTeamSpeakId.equals(myTeamSpeakId)) return c;
} }
return null; return null;
} }
/** Notes which myTeamSpeak ID a client carries (empty for none), so {@link #find} can match it. */
public void link(String uniqueId, String myTeamSpeakId) {
if (uniqueId == null || uniqueId.isEmpty()) return;
if (myTeamSpeakId == null || myTeamSpeakId.isEmpty()) myTsIds.remove(uniqueId);
else myTsIds.put(uniqueId, myTeamSpeakId);
}
/** The type a client is filed under, {@code null} when it is not a contact. */ /** The type a client is filed under, {@code null} when it is not a contact. */
public ContactType typeOf(String uniqueId) { public ContactType typeOf(String uniqueId) {
Contact c = find(uniqueId); Contact c = find(uniqueId);
@@ -163,35 +189,38 @@ public final class ContactStore {
public Contact add(String uniqueId, String nickname, ContactType type, ContactDefaults defaults) { public Contact add(String uniqueId, String nickname, ContactType type, ContactDefaults defaults) {
Contact contact; Contact contact;
synchronized (this) { synchronized (this) {
contact = byUid.get(uniqueId); contact = find(uniqueId);
if (contact == null) { if (contact == null) {
contact = new Contact(uniqueId); contact = new Contact(uniqueId);
contact.nickname = nickname == null ? "" : nickname; contact.nickname = nickname == null ? "" : nickname;
contact.applyDefaults(defaults.of(type)); contact.applyDefaults(defaults.of(type));
byUid.put(uniqueId, contact); byKey.put(contact.key(), contact);
} }
contact.type = type; contact.type = type;
snapshot = List.copyOf(byUid.values()); snapshot = List.copyOf(byKey.values());
} }
changed(); changed();
return contact; return contact;
} }
/** Stores an edited contact, replacing any entry with the same unique id. */ /** Stores an edited contact, replacing any entry with the same {@link Contact#key()}. */
public void put(Contact contact) { public void put(Contact contact) {
synchronized (this) { synchronized (this) {
Contact existing = byUid.get(contact.uniqueId); Contact existing = byKey.get(contact.key());
if (existing != null && existing != contact) existing.copyFrom(contact); if (existing != null && existing != contact) existing.copyFrom(contact);
else byUid.put(contact.uniqueId, contact); else byKey.put(contact.key(), contact);
snapshot = List.copyOf(byUid.values()); snapshot = List.copyOf(byKey.values());
} }
changed(); changed();
} }
/** Removes the contact {@link #find} gives for the id. */
public void remove(String uniqueId) { public void remove(String uniqueId) {
synchronized (this) { synchronized (this) {
if (byUid.remove(uniqueId) == null) return; Contact contact = find(uniqueId);
snapshot = List.copyOf(byUid.values()); if (contact == null) return;
byKey.remove(contact.key());
snapshot = List.copyOf(byKey.values());
} }
changed(); changed();
} }
@@ -199,9 +228,9 @@ public final class ContactStore {
/** Takes over a whole list, e.g. one read from the TeamSpeak client. */ /** Takes over a whole list, e.g. one read from the TeamSpeak client. */
public void replaceAll(Collection<Contact> contacts) { public void replaceAll(Collection<Contact> contacts) {
synchronized (this) { synchronized (this) {
byUid.clear(); byKey.clear();
for (Contact c : contacts) byUid.put(c.uniqueId, c); for (Contact c : contacts) byKey.put(c.key(), c);
snapshot = List.copyOf(byUid.values()); snapshot = List.copyOf(byKey.values());
} }
changed(); changed();
} }
@@ -216,9 +245,9 @@ public final class ContactStore {
int added = 0; int added = 0;
synchronized (this) { synchronized (this) {
for (Contact c : contacts) { for (Contact c : contacts) {
if (byUid.put(c.uniqueId, c) == null) added++; if (byKey.put(c.key(), c) == null) added++;
} }
snapshot = List.copyOf(byUid.values()); snapshot = List.copyOf(byKey.values());
} }
changed(); changed();
return added; return added;
@@ -198,11 +198,11 @@ public enum HotkeyAction {
// ----- Misc ----- // ----- Misc -----
TALK_POWER_GRANT_NEXT(Category.MISC, 0x01b0, "GrantNextTalkPower", TALK_POWER_GRANT_NEXT(Category.MISC, 0x01b0, "GrantNextTalkPower",
"Grant Next User Talk Power", true, Argument.NONE, false), "Grant Next User Talk Power", true, Argument.NONE, true),
TALK_POWER_REQUEST(Category.MISC, 0x01b0, "RequestTalkPower", TALK_POWER_REQUEST(Category.MISC, 0x01b0, "RequestTalkPower",
"Request Talk Power", true, Argument.NONE, false), "Request Talk Power", true, Argument.NONE, true),
TALK_POWER_REVOKE_ALL_GRANT_NEXT(Category.MISC, 0x01b0, "RevokeAllAndGrantNext", TALK_POWER_REVOKE_ALL_GRANT_NEXT(Category.MISC, 0x01b0, "RevokeAllAndGrantNext",
"Revoke All And Grant Next User Talk Power", true, Argument.NONE, false), "Revoke All And Grant Next User Talk Power", true, Argument.NONE, true),
FILEBROWSER(Category.MISC, 0x01d0, "Filebrowser", FILEBROWSER(Category.MISC, 0x01d0, "Filebrowser",
"Open Filebrowser on Channel", true, Argument.NONE, true), "Open Filebrowser on Channel", true, Argument.NONE, true),
@@ -12,27 +12,8 @@ import java.time.Instant;
*/ */
public record AccountInfo(String username, String userId, String uuid, Instant created) { public record AccountInfo(String username, String userId, String uuid, Instant created) {
private static final String BASE32 = "abcdefghijklmnopqrstuvwxyz234567";
static AccountInfo of(String username, String uuid, byte[] userId, long createdSeconds) { static AccountInfo of(String username, String uuid, byte[] userId, long createdSeconds) {
return new AccountInfo(username, userId == null ? "" : base32(userId), uuid, return new AccountInfo(username, userId == null ? "" : MyTsId.base32(userId), uuid,
createdSeconds > 0 ? Instant.ofEpochSecond(createdSeconds) : null); createdSeconds > 0 ? Instant.ofEpochSecond(createdSeconds) : null);
} }
/** RFC 4648 base32, lowercase and unpadded. */
static String base32(byte[] data) {
StringBuilder out = new StringBuilder((data.length * 8 + 4) / 5);
int buffer = 0, bits = 0;
for (byte b : data) {
buffer = (buffer << 8) | (b & 0xff);
bits += 8;
while (bits >= 5) {
out.append(BASE32.charAt((buffer >> (bits - 5)) & 31));
bits -= 5;
}
buffer &= (1 << bits) - 1;
}
if (bits > 0) out.append(BASE32.charAt((buffer << (5 - bits)) & 31));
return out.toString();
}
} }
@@ -11,12 +11,16 @@ import java.net.URI;
import java.security.GeneralSecurityException; import java.security.GeneralSecurityException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
/** /**
* Reads the bookmarks and identities a myTeamSpeak account synchronises, the way * Reads the bookmarks, identities and contacts a myTeamSpeak account synchronises, the way
* the official client pulls them on a fresh install: sign in, ask for every item * the official client pulls them on a fresh install: sign in, ask for every item
* of the wanted classes against an empty local state, decrypt them, and sign out. * of the wanted classes against an empty local state, decrypt them, and sign out.
* Nothing is ever written to the account. Staying signed in is {@link MyTeamSpeakLogin}'s. * {@link #pull} and {@link #push} are the two halves of synchronising, which
* {@link MyTeamSpeakSync} drives. Staying signed in is {@link MyTeamSpeakLogin}'s.
* *
* <p>The protocol is described in {@code docs/myteamspeak/PROTOCOL.md}. * <p>The protocol is described in {@code docs/myteamspeak/PROTOCOL.md}.
*/ */
@@ -41,11 +45,16 @@ public final class MyTeamSpeak {
public long bookmarks() { public long bookmarks() {
return items.stream().filter(SyncItem.Bookmark.class::isInstance).count(); return items.stream().filter(SyncItem.Bookmark.class::isInstance).count();
} }
public long contacts() {
return items.stream().filter(SyncItem.Contact.class::isInstance).count();
}
} }
private static final String NO_VERSION = "00000000-0000-0000-0000-000000000000"; static final String NO_VERSION = "00000000-0000-0000-0000-000000000000";
private static final int SYNC_VERSION_1_1 = 1; private static final int SYNC_VERSION_1_1 = 1;
private static final int[] ITEM_CLASSES = {0 /* BOOKMARK */, 1 /* IDENTITY */, 6 /* ITEM_FOLDER */}; private static final int CONTACTS = 8;
private static final int[] ITEM_CLASSES = {0 /* BOOKMARK */, 1 /* IDENTITY */, 6 /* ITEM_FOLDER */, CONTACTS};
private static final int LOGIN_OK = 200; private static final int LOGIN_OK = 200;
private static final int LOGIN_OFFLINE = 201; private static final int LOGIN_OFFLINE = 201;
@@ -99,21 +108,33 @@ public final class MyTeamSpeak {
public Account download(Credentials credentials) throws IOException, MyTsException { public Account download(Credentials credentials) throws IOException, MyTsException {
Session session = signIn(credentials); Session session = signIn(credentials);
try { try {
if (session.keyPackage == null) throw new MyTsException("The account has no synchronisation key", 0); return read(session, credentials);
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 { } finally {
signOut(session.id); signOut(session.id);
} }
} }
/** Reads the account in a signed-in session. */
Account read(Session session, Credentials credentials) throws IOException, MyTsException {
return new Account(session.info, pull(session.id, itemKey(credentials, session)));
}
/** A signed-in session: the bearer token later requests carry, and who it belongs to. */ /** A signed-in session: the bearer token later requests carry, and who it belongs to. */
record Session(String id, AccountInfo info, byte[] keyPackage) { record Session(String id, AccountInfo info, byte[] keyPackage, byte[] userId, long createdAt,
byte[] publicKey, byte[] encryptedPrivateKey, byte[] publicSignature) {
}
/** Reads only the server identity; does not download cloud items. */
MyTeamSpeakIdentity serverIdentity(Session session, Credentials credentials) throws MyTsException {
byte[] itemKey = itemKey(credentials, session);
try {
return new MyTeamSpeakIdentity(session.userId, session.createdAt, session.publicKey,
session.encryptedPrivateKey, session.publicSignature, itemKey);
} catch (GeneralSecurityException e) {
throw new MyTsException("Could not unlock the myTeamSpeak server identity", e);
} finally {
java.util.Arrays.fill(itemKey, (byte) 0);
}
} }
/** Signs in; the caller ends the session with {@link #signOut}. */ /** Signs in; the caller ends the session with {@link #signOut}. */
@@ -124,6 +145,7 @@ public final class MyTeamSpeak {
byte[] keyPackage = null; byte[] keyPackage = null;
String session = "", username = "", uuid = ""; String session = "", username = "", uuid = "";
byte[] userId = null; byte[] userId = null;
byte[] publicKey = null, encryptedPrivateKey = null, publicSignature = null;
long createdAt = 0; long createdAt = 0;
int error = 0; int error = 0;
while (reply.next()) { while (reply.next()) {
@@ -137,8 +159,17 @@ public final class MyTeamSpeak {
ProtobufReader identity = reply.readMessage(); ProtobufReader identity = reply.readMessage();
while (identity.next()) { while (identity.next()) {
switch (identity.fieldNumber()) { switch (identity.fieldNumber()) {
case 1 -> publicKey = identity.readBytes();
case 2 -> {
ProtobufReader key = identity.readMessage();
while (key.next()) {
if (key.fieldNumber() == 1) encryptedPrivateKey = key.readBytes();
else key.skip();
}
}
case 3 -> createdAt = identity.readVarint(); case 3 -> createdAt = identity.readVarint();
case 4 -> userId = identity.readBytes(); case 4 -> userId = identity.readBytes();
case 5 -> publicSignature = identity.readBytes();
default -> identity.skip(); default -> identity.skip();
} }
} }
@@ -147,80 +178,242 @@ public final class MyTeamSpeak {
} }
} }
if (error != LOGIN_OK) throw loginError(error); if (error != LOGIN_OK) throw loginError(error);
return new Session(session, AccountInfo.of(username, uuid, userId, createdAt), keyPackage); return new Session(session, AccountInfo.of(username, uuid, userId, createdAt), keyPackage,
userId, createdAt, publicKey, encryptedPrivateKey, publicSignature);
} }
private List<SyncItem> pull(String session, byte[] itemKey) throws IOException, MyTsException { private List<SyncItem> pull(String session, byte[] itemKey) throws IOException, MyTsException {
ProtobufWriter request = new ProtobufWriter().string(1, session); Map<Integer, String> cursors = new TreeMap<>();
for (int itemClass : ITEM_CLASSES) { for (int itemClass : ITEM_CLASSES) cursors.put(itemClass, NO_VERSION);
request.message(2, new ProtobufWriter().varint(1, itemClass).string(2, NO_VERSION)); SyncReply reply = exchange(session, "requestServerItems", NO_VERSION, cursors, Map.of());
}
request.string(3, NO_VERSION).varint(4, SYNC_VERSION_1_1); List<SyncItem> items = new ArrayList<>();
ProtobufReader reply = new ProtobufReader( for (int wanted : ITEM_CLASSES) {
transport.call("synchronization", "requestServerItems", request.toByteArray())); SyncReply.ItemClass itemClass = reply.classes.get(wanted);
if (itemClass == null) continue;
for (SyncReply.Detail detail : itemClass.details) {
if (detail.deleted || detail.blob == null || detail.blob.length == 0) continue;
SyncItem item = decode(wanted, detail.blob, itemKey);
if (item != null) items.add(item);
}
}
return SyncOrder.sorted(items);
}
/** One item as the account holds it: its class, identity, the server's revision of it and its plain {@code Item_Data}. */
record CloudItem(int itemClass, String uuid, String version, byte[] data) {
}
/**
* What changed in the account since the given cursors.
*
* @param global the account-wide cursor, which the official client sends back with every request
* @param cursors every class's cursor now, to send next time
* @param changed the classes asked for that changed, each with all of its items; a class
* not in here is as it was
*/
record Pull(String global, Map<Integer, String> cursors, Map<Integer, List<CloudItem>> changed) {
}
/**
* Reads the classes that changed since {@code cursors} (all of them for an empty map),
* decrypting the items of the {@code wanted} ones.
*/
Pull pull(Session session, Credentials credentials, String global, Map<Integer, String> cursors,
Set<Integer> wanted) throws IOException, MyTsException {
byte[] itemKey = itemKey(credentials, session);
SyncReply reply = exchange(session.id, "requestServerItems", global, advertised(cursors, wanted), Map.of());
Map<Integer, String> now = new TreeMap<>(cursors);
Map<Integer, List<CloudItem>> changed = new TreeMap<>();
for (SyncReply.ItemClass itemClass : reply.classes.values()) {
if (itemClass.notInDb) {
now.remove(itemClass.id);
if (wanted.contains(itemClass.id) && cursors.containsKey(itemClass.id)) {
changed.put(itemClass.id, List.of());
}
continue;
}
now.put(itemClass.id, itemClass.version);
if (!wanted.contains(itemClass.id)) continue;
List<CloudItem> items = new ArrayList<>();
for (SyncReply.Detail detail : itemClass.details) {
if (detail.deleted || detail.blob == null || detail.blob.length == 0) continue;
try {
items.add(new CloudItem(itemClass.id, detail.uuid, detail.version,
MyTsCrypto.decryptItem(detail.blob, itemKey)));
} catch (GeneralSecurityException e) {
throw new MyTsException("Could not decrypt the account's items", e);
}
}
changed.put(itemClass.id, items);
}
return new Pull(reply.global.isEmpty() ? global : reply.global, now, changed);
}
/** New contents for one class: its new revision, and the items to store; one without data is deleted. */
record ClassUpload(String version, List<CloudItem> items) {
}
/**
* Stores items in the account, but only if none of the {@code watched} classes changed since
* {@code cursors}: the server takes whatever it is sent, so the check is the client's.
*
* @return the account-wide cursor after the change
* @throws MyTsException {@link MyTsException#CHANGED_MEANWHILE} when one did
*/
String push(Session session, Credentials credentials, String global, Map<Integer, String> cursors,
Set<Integer> watched, Map<Integer, ClassUpload> uploads) throws IOException, MyTsException {
byte[] itemKey = itemKey(credentials, session);
SyncReply now = exchange(session.id, "requestServerItems", global, advertised(cursors, watched), Map.of());
for (int itemClass : watched) {
SyncReply.ItemClass reply = now.classes.get(itemClass);
boolean known = cursors.containsKey(itemClass);
if (reply != null && (known || !reply.notInDb)) {
throw new MyTsException("myTeamSpeak changed meanwhile; synchronize again", MyTsException.CHANGED_MEANWHILE);
}
}
Map<Integer, String> versions = new TreeMap<>();
Map<Integer, List<SyncReply.Detail>> details = new TreeMap<>();
for (Map.Entry<Integer, ClassUpload> upload : uploads.entrySet()) {
versions.put(upload.getKey(), upload.getValue().version());
List<SyncReply.Detail> list = new ArrayList<>();
for (CloudItem item : upload.getValue().items()) {
try {
list.add(item.data() == null
? new SyncReply.Detail(item.uuid(), item.version(), null, true)
: new SyncReply.Detail(item.uuid(), item.version(),
MyTsCrypto.encryptItem(item.data(), itemKey), false));
} catch (GeneralSecurityException e) {
throw new MyTsException("This platform lacks the ciphers myTeamSpeak needs", e);
}
}
details.put(upload.getKey(), list);
}
SyncReply stored = exchange(session.id, "synchronizeItems", global, versions, details);
if (stored.status != IN_SYNC) {
throw new MyTsException("myTeamSpeak did not store the changes (status " + stored.status + ")",
stored.status);
}
return stored.global;
}
/** The cursors to send: every known one, and none yet for a wanted class never seen, so it comes whole. */
private static Map<Integer, String> advertised(Map<Integer, String> cursors, Set<Integer> wanted) {
Map<Integer, String> out = new TreeMap<>(cursors);
for (int itemClass : wanted) out.putIfAbsent(itemClass, NO_VERSION);
return out;
}
private static byte[] itemKey(Credentials credentials, Session session) throws MyTsException {
if (session.keyPackage == null) throw new MyTsException("The account has no synchronisation key", 0);
try {
return MyTsCrypto.unwrapItemKey(credentials.accountKey(), session.keyPackage);
} catch (GeneralSecurityException e) {
throw new MyTsException("Could not unlock the account's encrypted data", e);
}
}
/** A {@code Sync_Reply_ItemClasses}. */
private record SyncReply(int status, String global, Map<Integer, ItemClass> classes) {
record ItemClass(int id, String version, boolean notInDb, List<Detail> details) {
}
record Detail(String uuid, String version, byte[] blob, boolean deleted) {
}
}
/**
* One synchronisation call: the cursor of each class and the details to send under it.
* Fails unless the server answered with a synchronisation status.
*/
private SyncReply exchange(String session, String method, String global, Map<Integer, String> versions,
Map<Integer, List<SyncReply.Detail>> details) throws IOException, MyTsException {
ProtobufWriter request = new ProtobufWriter().string(1, session);
for (Map.Entry<Integer, String> cursor : versions.entrySet()) {
ProtobufWriter itemClass = new ProtobufWriter().varint(1, cursor.getKey()).string(2, cursor.getValue());
for (SyncReply.Detail d : details.getOrDefault(cursor.getKey(), List.of())) {
ProtobufWriter detail = new ProtobufWriter().string(1, d.uuid()).string(2, d.version());
if (d.blob() != null) detail.bytes(3, d.blob());
if (d.deleted()) detail.varint(4, 1);
itemClass.message(3, detail);
}
request.message(2, itemClass);
}
request.string(3, global).varint(4, SYNC_VERSION_1_1);
ProtobufReader reply = new ProtobufReader(transport.call("synchronization", method, request.toByteArray()));
List<byte[]> frames = new ArrayList<>();
int status = 0; int status = 0;
String replyGlobal = "";
Map<Integer, SyncReply.ItemClass> classes = new TreeMap<>();
while (reply.next()) { while (reply.next()) {
switch (reply.fieldNumber()) { switch (reply.fieldNumber()) {
case 1 -> status = (int) reply.readVarint(); case 1 -> status = (int) reply.readVarint();
case 2 -> collectFrames(reply.readMessage(), frames); case 2 -> {
SyncReply.ItemClass itemClass = itemClass(reply.readMessage());
classes.put(itemClass.id(), itemClass);
}
case 3 -> replyGlobal = reply.readString();
default -> reply.skip(); default -> reply.skip();
} }
} }
if (status < IN_SYNC || status > NOT_IN_DB) { if (status < IN_SYNC || status > NOT_IN_DB) {
throw new MyTsException("myTeamSpeak refused to synchronise (status " + status + ")", status); throw new MyTsException("myTeamSpeak refused to synchronise (status " + status + ")", status);
} }
return new SyncReply(status, replyGlobal, classes);
}
List<SyncItem> items = new ArrayList<>(); private static SyncReply.ItemClass itemClass(ProtobufReader r) throws IOException {
for (byte[] frame : frames) { int id = 0;
SyncItem item; String version = "";
try { boolean notInDb = false;
item = SyncItemDecoder.decode(MyTsCrypto.decryptItem(frame, itemKey)); List<SyncReply.Detail> details = new ArrayList<>();
} catch (GeneralSecurityException e) { while (r.next()) {
throw new MyTsException("Could not decrypt the account's items", e); switch (r.fieldNumber()) {
case 1 -> id = (int) r.readVarint();
case 2 -> version = r.readString();
case 3 -> details.add(detail(r.readMessage()));
case 4 -> notInDb = r.readBool();
default -> r.skip();
} }
if (item != null) items.add(item);
} }
return SyncOrder.sorted(items); return new SyncReply.ItemClass(id, version, notInDb, details);
}
private static SyncReply.Detail detail(ProtobufReader r) throws IOException {
String uuid = "", version = "";
byte[] blob = null;
boolean deleted = false;
while (r.next()) {
switch (r.fieldNumber()) {
case 1 -> uuid = r.readString();
case 2 -> version = r.readString();
case 3 -> blob = r.readBytes();
case 4 -> deleted = r.readBool();
default -> r.skip();
}
}
return new SyncReply.Detail(uuid, version, blob, deleted);
} }
/** /**
* The encrypted items of one {@code Sync_ItemClasses_Data}; tombstones carry none. * Contacts are TeamSpeak 6's and were never seen in an account, so one that does not
* The server answers with every class the account holds, whatever was asked for, * decrypt is taken for plaintext, like add-on flags, or else left out — not allowed to
* and not all of them are encrypted (add-on flags come in the clear), so only the * fail the bookmarks and identities.
* wanted classes are kept.
*/ */
private static void collectFrames(ProtobufReader itemClass, List<byte[]> frames) throws IOException { private static SyncItem decode(int itemClass, byte[] blob, byte[] itemKey) throws IOException, MyTsException {
int classId = 0; try {
List<byte[]> blobs = new ArrayList<>(); return SyncItemDecoder.decode(MyTsCrypto.decryptItem(blob, itemKey));
while (itemClass.next()) { } catch (GeneralSecurityException e) {
switch (itemClass.fieldNumber()) { if (itemClass != CONTACTS) throw new MyTsException("Could not decrypt the account's items", e);
case 1 -> classId = (int) itemClass.readVarint();
case 3 -> {
byte[] blob = itemBlob(itemClass.readMessage());
if (blob != null) blobs.add(blob);
} }
default -> itemClass.skip(); try {
SyncItem item = SyncItemDecoder.decode(blob);
return item instanceof SyncItem.Contact ? item : null;
} catch (IOException | RuntimeException notPlaintext) {
return null;
} }
} }
for (int wanted : ITEM_CLASSES) {
if (wanted == classId) frames.addAll(blobs);
}
}
private static byte[] itemBlob(ProtobufReader detail) throws IOException {
byte[] blob = null;
boolean deleted = false;
while (detail.next()) {
switch (detail.fieldNumber()) {
case 3 -> blob = detail.readBytes();
case 4 -> deleted = detail.readBool();
default -> detail.skip();
}
}
return !deleted && blob != null && blob.length > 0 ? blob : null;
}
/** Ends the session rather than leave it for the server to expire; nothing to do if that fails. */ /** Ends the session rather than leave it for the server to expire; nothing to do if that fails. */
void signOut(String session) { void signOut(String session) {
@@ -0,0 +1,88 @@
package eu.lixko.ts3j.client.myts;
import Punisher.NaCl.Internal.Ed25519Ref10.GroupElementP3;
import Punisher.NaCl.Internal.Ed25519Ref10.GroupOperations;
import Punisher.NaCl.Internal.Ed25519Ref10.ScalarOperations;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.Map;
/** Account identity used to authenticate to voice servers. Never persisted or logged. */
public final class MyTeamSpeakIdentity implements AutoCloseable {
private final byte[] scalar;
private final byte[] publicKey;
private final Map<String, String> parameters;
private boolean closed;
MyTeamSpeakIdentity(byte[] id, long created, byte[] publicKey, byte[] encryptedKey,
byte[] certificate, byte[] itemKey) throws GeneralSecurityException {
if (id == null || id.length != 33 || publicKey == null || publicKey.length != 32
|| encryptedKey == null || encryptedKey.length != 112
|| certificate == null || certificate.length != 176)
throw new GeneralSecurityException("Incomplete myTeamSpeak server identity");
this.publicKey = publicKey.clone();
scalar = MyTsCrypto.decryptItem(encryptedKey, itemKey);
if (!MessageDigest.isEqual(point(scalar), publicKey)) {
Arrays.fill(scalar, (byte) 0);
throw new GeneralSecurityException("myTeamSpeak private key does not match its public key");
}
Base64.Encoder b64 = Base64.getEncoder();
parameters = new LinkedHashMap<>();
parameters.put("myTeamspeakId", b64.encodeToString(id));
parameters.put("acTime", Long.toUnsignedString(Long.reverseBytes(created)));
parameters.put("userPubKey", b64.encodeToString(publicKey));
parameters.put("pubSign", b64.encodeToString(Arrays.copyOf(certificate, 64)));
parameters.put("pubSignCert", b64.encodeToString(Arrays.copyOfRange(certificate, 64, 176)));
}
/** Fresh signature for a handshake; closing the identity disables subsequent announcements. */
public synchronized Map<String, String> authenticate(byte[] challenge) {
if (closed) return Map.of();
if (challenge.length != 32) throw new IllegalArgumentException("Expected a 32-byte connection challenge");
byte[] message = Arrays.copyOf(challenge, 45);
System.arraycopy("MyTeamSpeakID".getBytes(StandardCharsets.US_ASCII), 0, message, 32, 13);
byte[] r = null, k = null, s = new byte[32];
try {
MessageDigest hash = MessageDigest.getInstance("SHA-512");
hash.update(scalar);
r = hash.digest(message);
ScalarOperations.sc_reduce(r);
byte[] R = point(r);
hash.update(R);
hash.update(publicKey);
k = hash.digest(message);
ScalarOperations.sc_reduce(k);
ScalarOperations.sc_muladd(s, k, scalar, r);
byte[] signature = Arrays.copyOf(R, 64);
System.arraycopy(s, 0, signature, 32, 32);
Map<String, String> result = new LinkedHashMap<>(parameters);
result.put("authSign", Base64.getEncoder().encodeToString(signature));
return result;
} catch (GeneralSecurityException e) {
throw new IllegalStateException("SHA-512 unavailable", e);
} finally {
if (r != null) Arrays.fill(r, (byte) 0);
if (k != null) Arrays.fill(k, (byte) 0);
Arrays.fill(s, (byte) 0);
}
}
private static byte[] point(byte[] scalar) {
GroupElementP3 point = new GroupElementP3();
GroupOperations.ge_scalarmult_base(point, scalar, 0);
byte[] encoded = new byte[32];
GroupOperations.ge_p3_tobytes(encoded, 0, point);
return encoded;
}
@Override
public synchronized void close() {
closed = true;
Arrays.fill(scalar, (byte) 0);
}
}
@@ -14,7 +14,8 @@ import java.util.Properties;
* The myTeamSpeak account this client stays signed in to. Signing in keeps the * 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 * {@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. * can be read again later without asking for the password; signing out forgets them.
* Each read signs in afresh; only {@link MyTsFiles} keeps a session. * Requests share one session, as the official client's do: signed in on first use, again
* when the service lets it run out, and ended on sign-out or {@link #endSession}.
*/ */
public final class MyTeamSpeakLogin { public final class MyTeamSpeakLogin {
@@ -24,6 +25,17 @@ public final class MyTeamSpeakLogin {
private final MyTeamSpeak service; private final MyTeamSpeak service;
private MyTeamSpeak.Credentials credentials; private MyTeamSpeak.Credentials credentials;
private String username = ""; private String username = "";
private MyTeamSpeakIdentity serverIdentity;
private MyTeamSpeak.Session session;
private MyTeamSpeak.Credentials sessionCredentials;
private final Object identityLoadLock = new Object();
private final Object sessionLock = new Object();
private long revision;
/** Changes whenever the signed-in account changes, including sign-out. */
public synchronized long revision() {
return revision;
}
MyTeamSpeakLogin(File file, MyTeamSpeak service) { MyTeamSpeakLogin(File file, MyTeamSpeak service) {
this.file = file; this.file = file;
@@ -55,12 +67,27 @@ public final class MyTeamSpeakLogin {
*/ */
public MyTeamSpeak.Account signIn(String email, String password) throws IOException, MyTsException { public MyTeamSpeak.Account signIn(String email, String password) throws IOException, MyTsException {
MyTeamSpeak.Credentials fresh = MyTeamSpeak.Credentials.derive(email.trim(), password); MyTeamSpeak.Credentials fresh = MyTeamSpeak.Credentials.derive(email.trim(), password);
MyTeamSpeak.Account account = service.download(fresh); MyTeamSpeak.Session started = service.signIn(fresh);
MyTeamSpeak.Account account;
try {
account = service.read(started, fresh);
} catch (IOException | MyTsException | RuntimeException e) {
service.signOut(started.id());
throw e;
}
MyTeamSpeak.Session previous;
synchronized (this) { synchronized (this) {
if (serverIdentity != null) serverIdentity.close();
serverIdentity = null;
previous = session;
session = started;
sessionCredentials = fresh;
credentials = fresh; credentials = fresh;
revision++;
username = account.username(); username = account.username();
write(); write();
} }
if (previous != null) service.signOut(previous.id());
return account; return account;
} }
@@ -71,13 +98,8 @@ public final class MyTeamSpeakLogin {
* @throws IllegalStateException when signed out * @throws IllegalStateException when signed out
*/ */
public MyTeamSpeak.Account fetch() throws IOException, MyTsException { public MyTeamSpeak.Account fetch() throws IOException, MyTsException {
MyTeamSpeak.Credentials current; return request((s, current) -> {
synchronized (this) { MyTeamSpeak.Account account = service.read(s, current);
if (credentials == null) throw new IllegalStateException("Not signed in to myTeamSpeak");
current = credentials;
}
try {
MyTeamSpeak.Account account = service.download(current);
synchronized (this) { synchronized (this) {
if (credentials == current && !account.username().equals(username)) { if (credentials == current && !account.username().equals(username)) {
username = account.username(); username = account.username();
@@ -85,6 +107,37 @@ public final class MyTeamSpeakLogin {
} }
} }
return account; return account;
});
}
/** A request made in the kept session. */
interface Request<T> {
T run(MyTeamSpeak.Session session, MyTeamSpeak.Credentials credentials) throws IOException, MyTsException;
}
/**
* Makes a request in the kept session, signing in when there is none or it ran out, and
* signing out if the server no longer takes the credentials.
*
* @throws IllegalStateException when signed out
*/
<T> T request(Request<T> request) throws IOException, MyTsException {
MyTeamSpeak.Credentials current;
synchronized (this) {
if (credentials == null) throw new IllegalStateException("Not signed in to myTeamSpeak");
current = credentials;
}
try {
MyTeamSpeak.Session s = session(current);
try {
return request.run(s, current);
} catch (MyTsException e) {
if (!e.sessionExpired()) throw e;
synchronized (this) {
if (session == s) session = null;
}
return request.run(session(current), current);
}
} catch (MyTsException e) { } catch (MyTsException e) {
if (!e.credentialsRejected()) throw e; if (!e.credentialsRejected()) throw e;
synchronized (this) { synchronized (this) {
@@ -95,6 +148,49 @@ public final class MyTeamSpeakLogin {
} }
} }
/**
* The kept session, signing in when there is none. One sign-in at a time, under its own lock:
* the requests behind it wait, but whoever only asks whether we are signed in does not.
*/
private MyTeamSpeak.Session session(MyTeamSpeak.Credentials current) throws IOException, MyTsException {
synchronized (sessionLock) {
MyTeamSpeak.Session stale;
synchronized (this) {
if (session != null && sessionCredentials == current) return session;
stale = session;
session = null;
sessionCredentials = null;
}
if (stale != null) service.signOut(stale.id());
MyTeamSpeak.Session started = service.signIn(current);
synchronized (this) {
if (credentials == current) {
session = started;
sessionCredentials = current;
return started;
}
}
service.signOut(started.id());
throw new MyTsException("Signed out of myTeamSpeak meanwhile", 0);
}
}
/** Ends the kept session, as on exit; the next request signs in again. Blocks for a request. */
public void endSession() {
MyTeamSpeak.Session ended;
synchronized (this) {
ended = session;
session = null;
sessionCredentials = null;
}
if (ended != null) service.signOut(ended.id());
}
/** Where {@link MyTeamSpeakSync} keeps what it last synchronised; it goes with the sign-in. */
File syncStateFile() {
return new File(file.getAbsoluteFile().getParentFile(), SyncState.FILE_NAME);
}
/** What signs in, or {@code null} when signed out. */ /** What signs in, or {@code null} when signed out. */
synchronized MyTeamSpeak.Credentials credentials() { synchronized MyTeamSpeak.Credentials credentials() {
return credentials; return credentials;
@@ -104,11 +200,46 @@ public final class MyTeamSpeakLogin {
return service; return service;
} }
/** Blocking account request on first use; cached in memory until sign-out. */
public MyTeamSpeakIdentity serverIdentity() throws IOException, MyTsException {
synchronized (identityLoadLock) {
MyTeamSpeak.Credentials current;
synchronized (this) {
if (credentials == null) return null;
if (serverIdentity != null) return serverIdentity;
current = credentials;
}
MyTeamSpeakIdentity loaded = request(service::serverIdentity);
synchronized (this) {
if (credentials != current) {
loaded.close();
return null;
}
serverIdentity = loaded;
return loaded;
}
}
}
/** Forgets the sign-in; the session ends in the background. */
public synchronized void signOut() { public synchronized void signOut() {
MyTeamSpeak.Session ended = session;
session = null;
sessionCredentials = null;
if (ended != null) {
Thread end = new Thread(() -> service.signOut(ended.id()), "myteamspeak-sign-out");
end.setDaemon(true);
end.start();
}
if (serverIdentity != null) serverIdentity.close();
serverIdentity = null;
credentials = null; credentials = null;
revision++;
username = ""; username = "";
//noinspection ResultOfMethodCallIgnored //noinspection ResultOfMethodCallIgnored
file.delete(); file.delete();
//noinspection ResultOfMethodCallIgnored
syncStateFile().delete();
} }
private void read() { private void read() {
@@ -0,0 +1,551 @@
package eu.lixko.ts3j.client.myts;
import eu.lixko.ts3j.client.config.Bookmarks;
import eu.lixko.ts3j.client.config.IdentityStore;
import eu.lixko.ts3j.client.config.Settings;
import eu.lixko.ts3j.client.proto.ProtobufMessage;
import eu.lixko.ts3j.client.proto.ProtobufReader;
import eu.lixko.ts3j.client.teamspeak.SyncItem;
import eu.lixko.ts3j.client.teamspeak.SyncItemDecoder;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.UUID;
/**
* Two-way synchronisation of bookmarks and identities with the signed-in myTeamSpeak account.
* Against what both sides held after the last run, a change on one side is carried to the other,
* deletions included; an item changed on both sides is a {@link Conflict} the user settles.
* The first run, with nothing to go by, pairs items up by identity key or bookmark name and
* address, and carries over whatever has no partner.
*
* <p>A run is four steps, so that the user can be asked in between and so that the stores are
* touched only on the thread that owns them: {@link #fetch} and {@link #upload} block on the
* network, {@link #plan} and {@link #apply} read and change the stores. Nothing changes on
* either side before {@link #upload}, and here only once it succeeded.
*
* <p>The server takes whatever it is sent, so detecting a conflict is up to the client; see
* {@code docs/myteamspeak/IMPLEMENTATION.md}.
*/
public final class MyTeamSpeakSync {
private static final int BOOKMARK = 0;
private static final int IDENTITY = 1;
private static final Set<Integer> CLASSES = Set.of(BOOKMARK, IDENTITY);
private static final int ITEM_ADDED = 0;
/** What the official client writes on every change it sends, though the flag reads "not manipulated". */
private static final int ITEM_COMMITTED = 3;
private final MyTeamSpeakLogin login;
private final IdentityStore identities;
private final Bookmarks bookmarks;
private final Settings settings;
private final File stateFile;
public MyTeamSpeakSync(MyTeamSpeakLogin login, IdentityStore identities, Bookmarks bookmarks, Settings settings) {
this.login = login;
this.identities = identities;
this.bookmarks = bookmarks;
this.settings = settings;
this.stateFile = login.syncStateFile();
}
/** The account as it is now, against how it was after the last run. */
public static final class Remote {
final String account;
final SyncState base;
final MyTeamSpeak.Pull pull;
Remote(String account, SyncState base, MyTeamSpeak.Pull pull) {
this.account = account;
this.base = base;
this.pull = pull;
}
}
/** What a run did. */
public record Result(int sent, int received) {
}
/** Step 1: reads what changed in the account. Blocks on the network. */
public Remote fetch() throws IOException, MyTsException {
return login.request((session, credentials) -> {
SyncState base = SyncState.load(stateFile, credentials.email());
return new Remote(credentials.email(), base,
login.service().pull(session, credentials, base.global, base.cursors, CLASSES));
});
}
/** Step 2: works out what goes which way, on the thread that owns the stores. */
public Plan plan(Remote remote) throws IOException {
SyncKind.Links links = new SyncKind.Links();
SyncKind identityKind = new SyncKind.IdentityKind(identities, bookmarks, settings, links);
SyncKind bookmarkKind = new SyncKind.BookmarkKind(identities, bookmarks, settings, links);
Map<Integer, List<MyTeamSpeak.CloudItem>> cloud = new HashMap<>();
Map<Integer, List<SyncState.Entry>> base = new HashMap<>();
for (int itemClass : CLASSES) {
base.put(itemClass, new ArrayList<>());
List<MyTeamSpeak.CloudItem> changed = remote.pull.changed().get(itemClass);
if (changed != null) cloud.put(itemClass, changed);
}
for (SyncState.Entry entry : remote.base.items.values()) {
if (!CLASSES.contains(entry.itemClass())) continue;
base.get(entry.itemClass()).add(entry);
if (!remote.pull.changed().containsKey(entry.itemClass())) {
cloud.computeIfAbsent(entry.itemClass(), k -> new ArrayList<>()).add(
new MyTeamSpeak.CloudItem(entry.itemClass(), entry.uuid(), entry.version(), entry.data()));
}
}
// Bookmarks name identities the cloud holds, now or before; the current ones take precedence.
for (MyTeamSpeak.CloudItem item : cloud.getOrDefault(IDENTITY, List.of())) {
if (decode(item.data()) instanceof SyncItem.Identity identity) links.addCloudIdentity(identity);
}
for (SyncState.Entry entry : base.get(IDENTITY)) {
if (decode(entry.data()) instanceof SyncItem.Identity identity) links.addCloudIdentity(identity);
}
Plan plan = new Plan(remote, links);
reconcile(plan, identityKind, base.get(IDENTITY), cloud.getOrDefault(IDENTITY, List.of()));
for (Step step : plan.allSteps()) {
if (step.kind == identityKind && step.localId != null && !step.localId.isEmpty()) {
links.uuidByLocal.put(step.localId, step.uuid);
}
}
reconcile(plan, bookmarkKind, base.get(BOOKMARK), cloud.getOrDefault(BOOKMARK, List.of()));
return plan;
}
/** Step 3: stores this side's changes in the account. Blocks on the network. */
public void upload(Plan plan) throws IOException, MyTsException {
if (!plan.isResolved()) throw new IllegalStateException("Unsettled conflicts");
Map<Integer, MyTeamSpeak.ClassUpload> uploads = new TreeMap<>();
Map<Integer, String> versions = new TreeMap<>();
Map<Integer, List<MyTeamSpeak.CloudItem>> items = new TreeMap<>();
for (Step step : plan.effectiveSteps()) {
if (step.upload == null) continue;
items.computeIfAbsent(step.kind.itemClass(), k -> new ArrayList<>()).add(step.upload);
}
for (Map.Entry<Integer, List<MyTeamSpeak.CloudItem>> e : items.entrySet()) {
String version = UUID.randomUUID().toString();
versions.put(e.getKey(), version);
uploads.put(e.getKey(), new MyTeamSpeak.ClassUpload(version, e.getValue()));
}
if (!uploads.isEmpty()) {
login.request((session, credentials) -> {
if (!credentials.email().equalsIgnoreCase(plan.remote.account)) {
throw new MyTsException("Signed in to another account meanwhile", MyTsException.CHANGED_MEANWHILE);
}
plan.uploadedGlobal = login.service().push(session, credentials, plan.remote.pull.global(),
plan.remote.pull.cursors(), CLASSES, uploads);
return null;
});
}
plan.uploadedVersions = versions;
}
/** Step 4: brings the account's changes here and remembers the outcome for the next run. */
public Result apply(Plan plan) throws IOException {
if (plan.uploadedVersions == null) throw new IllegalStateException("Not uploaded");
SyncState state = new SyncState();
state.cursors.putAll(plan.remote.pull.cursors());
state.cursors.putAll(plan.uploadedVersions);
state.global = plan.uploadedGlobal != null ? plan.uploadedGlobal : plan.remote.pull.global();
// Unmodelled classes keep what the last run knew of them.
for (SyncState.Entry entry : plan.remote.base.items.values()) {
if (!CLASSES.contains(entry.itemClass())) state.items.put(entry.uuid(), entry);
}
int sent = 0, received = 0;
for (Step step : plan.effectiveSteps()) {
int itemClass = step.kind.itemClass();
switch (step.action) {
case KEEP -> keep(state, step.cloud, step.localId);
case PUSH -> {
state.items.put(step.uuid, new SyncState.Entry(itemClass, step.uuid, step.upload.version(),
step.localId, step.upload.data()));
sent++;
}
case PUSH_DELETE -> sent++;
case PULL -> {
SyncItem item = decode(step.cloud.data());
String localId = step.localId == null || step.localId.isEmpty()
? step.kind.add(item) : step.kind.update(step.localId, item);
keep(state, step.cloud, localId);
received++;
}
case PULL_DELETE -> {
step.kind.remove(step.localId);
received++;
}
case FORGET -> {
}
}
if (itemClass == IDENTITY && state.items.containsKey(step.uuid)) {
plan.links.localByUuid.put(step.uuid, state.items.get(step.uuid).localId());
}
}
bookmarks.save();
settings.save();
state.save(stateFile, plan.remote.account);
return new Result(sent, received);
}
private static void keep(SyncState state, MyTeamSpeak.CloudItem item, String localId) {
state.items.put(item.uuid(), new SyncState.Entry(item.itemClass(), item.uuid(), item.version(),
localId == null ? "" : localId, item.data()));
}
/**
* The three-way comparison of one class: what the last run left (base), what is here
* (local) and what is in the account (cloud).
*/
private void reconcile(Plan plan, SyncKind kind, List<SyncState.Entry> base, List<MyTeamSpeak.CloudItem> cloud)
throws IOException {
Map<String, MyTeamSpeak.CloudItem> cloudByUuid = new LinkedHashMap<>();
for (MyTeamSpeak.CloudItem item : cloud) cloudByUuid.put(item.uuid(), item);
Set<String> claimed = new HashSet<>();
// What local items the account's items stand for, by match key.
Set<String> linked = new HashSet<>();
for (SyncState.Entry entry : base) {
MyTeamSpeak.CloudItem now = cloudByUuid.remove(entry.uuid());
SyncFields baseFields = fieldsOf(kind, entry.data());
if (baseFields == null || entry.localId().isEmpty()) {
// Not something this client models: left as the account has it.
if (now != null) plan.add(Step.keep(kind, now, ""));
continue;
}
if (claimed.contains(entry.localId())) {
// Two account items on one local item: only the first is synchronised.
if (now != null) plan.add(Step.keep(kind, now, ""));
continue;
}
SyncFields local = kind.localFields(entry.localId());
if (local != null) {
claimed.add(entry.localId());
linked.add(kind.matchKey(local));
}
SyncFields remote = now == null ? null : fieldsOf(kind, now.data());
if (now != null && remote == null) {
plan.add(Step.keep(kind, now, ""));
continue;
}
boolean localChanged = local != null && !local.sameAs(baseFields);
boolean cloudChanged = now != null && !now.version().equals(entry.version());
// Lost only its identity, deleted here: whether that stands is the identity's conflict.
Conflict restoring = now == null ? null : restoredWith(plan, kind, entry, local, baseFields);
if (now == null && local == null) {
plan.add(new Step(kind, Action.FORGET, entry.uuid(), entry.localId(), null, null));
} else if (now == null) {
Step delete = new Step(kind, Action.PULL_DELETE, entry.uuid(), entry.localId(), null, null);
if (!localChanged) {
plan.add(delete);
} else {
plan.conflict(kind, local, null, push(kind, entry.uuid(), entry.localId(),
new MyTeamSpeak.CloudItem(kind.itemClass(), entry.uuid(), entry.version(), entry.data()),
true), delete);
}
} else if (local == null) {
Step delete = new Step(kind, Action.PUSH_DELETE, entry.uuid(), entry.localId(), null,
new MyTeamSpeak.CloudItem(kind.itemClass(), entry.uuid(), UUID.randomUUID().toString(), null));
if (!cloudChanged) plan.add(delete);
else plan.deletedHere.put(entry.uuid(),
plan.conflict(kind, null, remote, delete, Step.pull(kind, now, null)));
} else if (restoring != null) {
Step pull = Step.pull(kind, now, entry.localId());
plan.contingent(restoring, cloudChanged ? pull : push(kind, entry.uuid(), entry.localId(), now, false),
pull);
} else if (!localChanged && !cloudChanged) {
plan.add(Step.keep(kind, now, entry.localId()));
} else if (!cloudChanged) {
plan.add(push(kind, entry.uuid(), entry.localId(), now, false));
} else if (!localChanged || local.sameAs(remote)) {
plan.add(local.sameAs(remote) ? Step.keep(kind, now, entry.localId())
: Step.pull(kind, now, entry.localId()));
} else {
plan.conflict(kind, local, remote, push(kind, entry.uuid(), entry.localId(), now, false),
Step.pull(kind, now, entry.localId()));
}
}
// New on either side: pair them up, carry over the rest.
Map<String, String> unpaired = new LinkedHashMap<>();
for (String localId : kind.localIds()) {
if (claimed.contains(localId)) continue;
SyncFields local = kind.localFields(localId);
if (local != null) unpaired.putIfAbsent(kind.matchKey(local), localId);
}
Set<String> paired = new HashSet<>();
for (MyTeamSpeak.CloudItem now : cloudByUuid.values()) {
SyncFields remote = fieldsOf(kind, now.data());
if (remote == null) {
plan.add(Step.keep(kind, now, ""));
continue;
}
String key = kind.matchKey(remote);
String localId = unpaired.remove(key);
if (localId == null) {
// One local item per key: another account item already stands for it.
if (kind.onePerKey() && linked.contains(key)) plan.add(Step.keep(kind, now, ""));
else plan.add(Step.pull(kind, now, null));
linked.add(key);
continue;
}
paired.add(localId);
linked.add(key);
SyncFields local = kind.localFields(localId);
if (local.sameAs(remote)) {
plan.add(Step.keep(kind, now, localId));
} else {
plan.conflict(kind, local, remote, push(kind, now.uuid(), localId, now, false),
Step.pull(kind, now, localId));
}
}
for (String localId : kind.localIds()) {
if (claimed.contains(localId) || paired.contains(localId)) continue;
plan.add(push(kind, UUID.randomUUID().toString(), localId, null, true));
}
}
/**
* Sending the local item as {@code uuid}: written over {@code onto}, keeping whatever this
* client does not model, or from scratch when there is nothing to write over.
*/
private static Step push(SyncKind kind, String uuid, String localId, MyTeamSpeak.CloudItem onto, boolean added)
throws IOException {
String version = UUID.randomUUID().toString();
SyncFields local = kind.localFields(localId);
ProtobufMessage item;
ProtobufMessage content;
Set<String> labels;
if (onto == null) {
item = new ProtobufMessage().string(2, uuid).string(3, version).varint(4, ITEM_ADDED)
.varint(6, kind.itemClass()).string(7, "").string(8, "");
content = new ProtobufMessage();
labels = new LinkedHashSet<>(local.values().keySet());
} else {
// Like the official client: the revision written over becomes the last known one, and a
// client holding that revision takes the change.
item = new ProtobufMessage(onto.data());
ProtobufReader previous = item.get(3);
if (previous != null) item.string(5, previous.readString());
item.string(3, version).varint(4, added ? ITEM_ADDED : ITEM_COMMITTED);
ProtobufReader existing = item.get(kind.contentField());
content = existing == null ? new ProtobufMessage() : new ProtobufMessage(existing.readBytes());
SyncFields before = fieldsOf(kind, onto.data());
labels = before == null ? new LinkedHashSet<>(local.values().keySet()) : local.changedFrom(before);
}
item.varint(9, System.currentTimeMillis() / 1000);
kind.write(localId, content, labels);
if (onto == null) kind.writeNew(localId, content);
item.message(kind.contentField(), content);
return new Step(kind, Action.PUSH, uuid, localId, null,
new MyTeamSpeak.CloudItem(kind.itemClass(), uuid, version, item.toByteArray()));
}
/**
* The conflict of the identity deleted here that the item was using, when losing it is all
* that changed about the item here.
*/
private static Conflict restoredWith(Plan plan, SyncKind kind, SyncState.Entry entry, SyncFields local,
SyncFields base) {
if (local == null) return null;
String identity = kind.identityUsed(entry.data());
Conflict conflict = identity == null ? null : plan.deletedHere.get(identity);
return conflict != null && kind.lostIdentityOnly(local, base) ? conflict : null;
}
private static SyncFields fieldsOf(SyncKind kind, byte[] data) {
SyncItem item = decode(data);
return item == null ? null : kind.cloudFields(item);
}
private static SyncItem decode(byte[] data) {
try {
return SyncItemDecoder.decode(data);
} catch (IOException | RuntimeException unreadable) {
return null;
}
}
private enum Action { KEEP, PUSH, PUSH_DELETE, PULL, PULL_DELETE, FORGET }
/**
* What happens to one item. {@code cloud} is the account's copy where there is one to keep or
* bring here; {@code upload} what is sent, without data for a deletion.
*/
private record Step(SyncKind kind, Action action, String uuid, String localId,
MyTeamSpeak.CloudItem cloud, MyTeamSpeak.CloudItem upload) {
static Step keep(SyncKind kind, MyTeamSpeak.CloudItem cloud, String localId) {
return new Step(kind, Action.KEEP, cloud.uuid(), localId, cloud, null);
}
static Step pull(SyncKind kind, MyTeamSpeak.CloudItem cloud, String localId) {
return new Step(kind, Action.PULL, cloud.uuid(), localId, cloud, null);
}
boolean sends() {
return action == Action.PUSH || action == Action.PUSH_DELETE;
}
boolean receives() {
return action == Action.PULL || action == Action.PULL_DELETE;
}
}
private record Contingent(Conflict on, Step ifHere, Step ifCloud) {
}
/** What a run will do, once its conflicts are settled. */
public static final class Plan {
final Remote remote;
final SyncKind.Links links;
private final List<Step> steps = new ArrayList<>();
private final List<Conflict> conflicts = new ArrayList<>();
private final List<Contingent> contingents = new ArrayList<>();
/** Conflicts of identities deleted here but changed in the account, by item UUID. */
final Map<String, Conflict> deletedHere = new HashMap<>();
/** The class revisions sent; set once {@link #upload} succeeded. */
volatile Map<Integer, String> uploadedVersions;
/** The account-wide cursor the upload left, {@code null} when nothing was sent. */
volatile String uploadedGlobal;
Plan(Remote remote, SyncKind.Links links) {
this.remote = remote;
this.links = links;
}
void add(Step step) {
steps.add(step);
}
Conflict conflict(SyncKind kind, SyncFields here, SyncFields cloud, Step keepHere, Step keepCloud) {
Conflict c = new Conflict(kind.title(here != null ? here : cloud),
kind instanceof SyncKind.IdentityKind, here, cloud, keepHere, keepCloud);
conflicts.add(c);
return c;
}
/** A step that follows how another item's conflict is settled. */
void contingent(Conflict on, Step ifHere, Step ifCloud) {
contingents.add(new Contingent(on, ifHere, ifCloud));
}
/** Every step either choice of a conflict could take, for the identity links. */
List<Step> allSteps() {
List<Step> out = new ArrayList<>(steps);
for (Conflict c : conflicts) {
out.add(c.keepHere);
out.add(c.keepCloud);
}
for (Contingent c : contingents) {
out.add(c.ifHere);
out.add(c.ifCloud);
}
return out;
}
/** The steps, the conflicts' as settled, identities before the bookmarks that use them. */
List<Step> effectiveSteps() {
List<Step> out = new ArrayList<>(steps);
for (Conflict c : conflicts) out.add(c.choice == Conflict.Choice.HERE ? c.keepHere : c.keepCloud);
for (Contingent c : contingents) out.add(c.on.choice == Conflict.Choice.HERE ? c.ifHere : c.ifCloud);
out.sort((a, b) -> Integer.compare(b.kind.itemClass(), a.kind.itemClass()));
return out;
}
public List<Conflict> conflicts() {
return List.copyOf(conflicts);
}
public boolean isResolved() {
return conflicts.stream().allMatch(c -> c.choice != null);
}
/** Items to send to the account, not counting conflicts. */
public int toSend() {
return (int) steps.stream().filter(Step::sends).count();
}
/** Items to bring here from the account, not counting conflicts. */
public int toReceive() {
return (int) steps.stream().filter(Step::receives).count();
}
}
/** An item changed both here and in the account since the last run. */
public static final class Conflict {
public enum Choice { HERE, CLOUD }
/** One synchronised field of the item, as each side has it; empty on a side where the item is gone. */
public record Difference(String label, String here, String cloud, boolean differs) {
}
private final String title;
private final boolean identity;
private final SyncFields here;
private final SyncFields cloud;
final Step keepHere;
final Step keepCloud;
private volatile Choice choice;
Conflict(String title, boolean identity, SyncFields here, SyncFields cloud, Step keepHere, Step keepCloud) {
this.title = title;
this.identity = identity;
this.here = here;
this.cloud = cloud;
this.keepHere = keepHere;
this.keepCloud = keepCloud;
}
public String title() {
return title;
}
/** An identity; otherwise a bookmark. */
public boolean isIdentity() {
return identity;
}
public boolean deletedHere() {
return here == null;
}
public boolean deletedInCloud() {
return cloud == null;
}
public List<Difference> differences() {
SyncFields any = here != null ? here : cloud;
List<Difference> out = new ArrayList<>();
for (String label : any.values().keySet()) {
String h = here == null ? "" : here.display(label);
String c = cloud == null ? "" : cloud.display(label);
boolean differs = here == null || cloud == null || !here.compare(label).equals(cloud.compare(label));
out.add(new Difference(label, h, c, differs));
}
return out;
}
public Choice choice() {
return choice;
}
public void choose(Choice choice) {
this.choice = choice;
}
}
}
@@ -8,6 +8,7 @@ import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException; import java.security.GeneralSecurityException;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Arrays; import java.util.Arrays;
import java.util.Base64; import java.util.Base64;
@@ -28,6 +29,7 @@ final class MyTsCrypto {
private static final int KEY_PACKAGE_VERSION = 2; private static final int KEY_PACKAGE_VERSION = 2;
private static final int CTR_BLOCK_BYTES = 16; private static final int CTR_BLOCK_BYTES = 16;
private static final int ITEM_HASH_BYTES = 64; private static final int ITEM_HASH_BYTES = 64;
private static final SecureRandom RANDOM = new SecureRandom();
private MyTsCrypto() { private MyTsCrypto() {
} }
@@ -68,23 +70,14 @@ final class MyTsCrypto {
/** /**
* Decrypts an item frame, {@code iv[16] || ciphertext || SHA-512(plaintext)}, into * Decrypts an item frame, {@code iv[16] || ciphertext || SHA-512(plaintext)}, into
* its {@code Item_Data} message. The cipher is AES-256-CTR, but with the counter * its {@code Item_Data} message.
* incremented little-endian, so JCA's own CTR mode cannot be used.
*/ */
static byte[] decryptItem(byte[] frame, byte[] itemKey) throws GeneralSecurityException { static byte[] decryptItem(byte[] frame, byte[] itemKey) throws GeneralSecurityException {
int textLength = frame.length - CTR_BLOCK_BYTES - ITEM_HASH_BYTES; int textLength = frame.length - CTR_BLOCK_BYTES - ITEM_HASH_BYTES;
if (textLength <= 0) throw new GeneralSecurityException("Truncated item"); if (textLength <= 0) throw new GeneralSecurityException("Truncated item");
Cipher aes = Cipher.getInstance("AES/ECB/NoPadding");
aes.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(itemKey, "AES"));
byte[] counter = Arrays.copyOf(frame, CTR_BLOCK_BYTES);
byte[] plain = new byte[textLength]; byte[] plain = new byte[textLength];
for (int off = 0; off < textLength; off += CTR_BLOCK_BYTES) { ctr(itemKey, Arrays.copyOf(frame, CTR_BLOCK_BYTES), frame, CTR_BLOCK_BYTES, plain, 0, textLength);
byte[] keyStream = aes.doFinal(counter);
int n = Math.min(CTR_BLOCK_BYTES, textLength - off);
for (int i = 0; i < n; i++) plain[off + i] = (byte) (frame[CTR_BLOCK_BYTES + off + i] ^ keyStream[i]);
incrementLittleEndian(counter);
}
byte[] hash = MessageDigest.getInstance("SHA-512").digest(plain); byte[] hash = MessageDigest.getInstance("SHA-512").digest(plain);
byte[] expected = Arrays.copyOfRange(frame, frame.length - ITEM_HASH_BYTES, frame.length); byte[] expected = Arrays.copyOfRange(frame, frame.length - ITEM_HASH_BYTES, frame.length);
@@ -92,6 +85,34 @@ final class MyTsCrypto {
return plain; return plain;
} }
/** The inverse of {@link #decryptItem}, under a fresh random IV. */
static byte[] encryptItem(byte[] plain, byte[] itemKey) throws GeneralSecurityException {
byte[] frame = new byte[CTR_BLOCK_BYTES + plain.length + ITEM_HASH_BYTES];
byte[] iv = new byte[CTR_BLOCK_BYTES];
RANDOM.nextBytes(iv);
System.arraycopy(iv, 0, frame, 0, CTR_BLOCK_BYTES);
ctr(itemKey, iv, plain, 0, frame, CTR_BLOCK_BYTES, plain.length);
byte[] hash = MessageDigest.getInstance("SHA-512").digest(plain);
System.arraycopy(hash, 0, frame, CTR_BLOCK_BYTES + plain.length, ITEM_HASH_BYTES);
return frame;
}
/**
* AES-256-CTR with the counter incremented little-endian, which JCA's own CTR mode
* cannot do. {@code counter} is consumed.
*/
private static void ctr(byte[] key, byte[] counter, byte[] in, int inAt, byte[] out, int outAt, int length)
throws GeneralSecurityException {
Cipher aes = Cipher.getInstance("AES/ECB/NoPadding");
aes.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"));
for (int off = 0; off < length; off += CTR_BLOCK_BYTES) {
byte[] keyStream = aes.doFinal(counter);
int n = Math.min(CTR_BLOCK_BYTES, length - off);
for (int i = 0; i < n; i++) out[outAt + off + i] = (byte) (in[inAt + off + i] ^ keyStream[i]);
incrementLittleEndian(counter);
}
}
/** PBKDF2-HMAC-SHA512 keyed by the password, salted with {@code lower(email) + purpose + password}. */ /** PBKDF2-HMAC-SHA512 keyed by the password, salted with {@code lower(email) + purpose + password}. */
private static byte[] derive(String email, String password, String purpose, int length) private static byte[] derive(String email, String password, String purpose, int length)
throws GeneralSecurityException { throws GeneralSecurityException {
@@ -5,6 +5,11 @@ public final class MyTsException extends Exception {
/** {@code ERROR_LOGIN_FAILED}: wrong email or password. */ /** {@code ERROR_LOGIN_FAILED}: wrong email or password. */
static final int LOGIN_FAILED = 202; static final int LOGIN_FAILED = 202;
/** A session the service no longer knows: {@code SyncStatus.ERROR_SESSION_EXPIRED}, the user service's own code. */
private static final int SYNC_SESSION_EXPIRED = 102;
private static final int USER_SESSION_EXPIRED = 109;
/** Ours, not the service's: the account changed between reading it and writing to it. */
static final int CHANGED_MEANWHILE = 1;
private final int code; private final int code;
@@ -23,6 +28,16 @@ public final class MyTsException extends Exception {
return code; return code;
} }
/** The account changed while a synchronisation was under way; reading it again resolves it. */
public boolean changedMeanwhile() {
return code == CHANGED_MEANWHILE;
}
/** The session ran out; signing in again resolves it. */
public boolean sessionExpired() {
return code == SYNC_SESSION_EXPIRED || code == USER_SESSION_EXPIRED;
}
/** The server no longer accepts the email and password, for instance after a password change. */ /** The server no longer accepts the email and password, for instance after a password change. */
public boolean credentialsRejected() { public boolean credentialsRejected() {
return code == LOGIN_FAILED; return code == LOGIN_FAILED;
@@ -13,8 +13,7 @@ import java.net.URL;
/** /**
* Files kept in myTeamSpeak cloud storage, as TeamSpeak 6 shares them in chat. The service * 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 * 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 * room, one to get a file someone put under theirs. Both need a signed-in account.
* 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 * <p>The storage addresses are signed for {@code Content-Type: text/plain} whatever the file
* is, both ways; a request without it is refused. * is, both ways; a request without it is refused.
@@ -29,8 +28,6 @@ public final class MyTsFiles {
private final MyTeamSpeakLogin login; private final MyTeamSpeakLogin login;
private final MyTeamSpeak service; private final MyTeamSpeak service;
private MyTeamSpeak.Session session;
private MyTeamSpeak.Credentials sessionCredentials;
public MyTsFiles(MyTeamSpeakLogin login) { public MyTsFiles(MyTeamSpeakLogin login) {
this(login, login.service()); this(login, login.service());
@@ -106,15 +103,9 @@ public final class MyTsFiles {
} }
} }
/** Ends the kept session, e.g. on sign-out or exit; the next request signs in again. */ /** Ends the account's session, e.g. on exit; the next request signs in again. */
public void close() { public void close() {
MyTeamSpeak.Session ended; login.endSession();
synchronized (this) {
ended = session;
session = null;
sessionCredentials = null;
}
if (ended != null) service.signOut(ended.id());
} }
private interface Request<T> { private interface Request<T> {
@@ -122,28 +113,11 @@ public final class MyTsFiles {
} }
private <T> T withSession(Request<T> request) throws IOException, MyTsException { private <T> T withSession(Request<T> request) throws IOException, MyTsException {
MyTeamSpeak.Session s = session(); if (!login.isSignedIn()) throw new MyTsException("Sign in to myTeamSpeak to share files", 0);
try { return login.request((session, credentials) -> {
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); if (session.info().userId().isEmpty()) throw new MyTsException("The account has no myTeamSpeak ID", 0);
return session; return request.run(session);
});
} }
private static HttpURLConnection open(String url) throws IOException { private static HttpURLConnection open(String url) throws IOException {
@@ -0,0 +1,60 @@
package eu.lixko.ts3j.client.myts;
import java.util.Base64;
/**
* The two spellings of a myTeamSpeak ID. Servers carry it as {@code client_myteamspeak_id},
* standard base64; TeamSpeak chat puts the same bytes, lowercase base32, in the localpart of
* the account's Matrix user ID ({@code @<base32>:<homeserver>}).
*/
public final class MyTsId {
private static final String BASE32 = "abcdefghijklmnopqrstuvwxyz234567";
private MyTsId() {
}
/** The myTeamSpeak ID behind a TeamSpeak chat user ID, or empty when it is not one. */
public static String fromChatId(String chatId) {
if (chatId == null || !chatId.startsWith("@")) return "";
int colon = chatId.indexOf(':');
if (colon < 2) return "";
byte[] id = base32Decode(chatId.substring(1, colon));
return id == null ? "" : Base64.getEncoder().encodeToString(id);
}
/** RFC 4648 base32, lowercase and unpadded. */
static String base32(byte[] data) {
StringBuilder out = new StringBuilder((data.length * 8 + 4) / 5);
int buffer = 0, bits = 0;
for (byte b : data) {
buffer = (buffer << 8) | (b & 0xff);
bits += 8;
while (bits >= 5) {
out.append(BASE32.charAt((buffer >> (bits - 5)) & 31));
bits -= 5;
}
buffer &= (1 << bits) - 1;
}
if (bits > 0) out.append(BASE32.charAt((buffer << (5 - bits)) & 31));
return out.toString();
}
/** The inverse of {@link #base32}, either case; {@code null} for anything else. */
static byte[] base32Decode(String text) {
byte[] out = new byte[text.length() * 5 / 8];
int buffer = 0, bits = 0, n = 0;
for (int i = 0; i < text.length(); i++) {
int value = BASE32.indexOf(Character.toLowerCase(text.charAt(i)));
if (value < 0) return null;
buffer = (buffer << 5) | value;
bits += 5;
if (bits >= 8) {
out[n++] = (byte) (buffer >> (bits - 8));
bits -= 8;
buffer &= (1 << bits) - 1;
}
}
return out;
}
}
@@ -0,0 +1,67 @@
package eu.lixko.ts3j.client.myts;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
/**
* The parts of a bookmark or identity that synchronise, by label, in the same terms whichever
* side they come from, so that two copies compare equal exactly when they agree.
*/
final class SyncFields {
/**
* @param compare what decides equality
* @param display what the user is shown; for a secret, only whether it is set
*/
record Value(String compare, String display) {
}
private final Map<String, Value> values = new LinkedHashMap<>();
SyncFields put(String label, String value) {
return put(label, value, value);
}
SyncFields put(String label, String compare, String display) {
values.put(label, new Value(compare == null ? "" : compare, display == null ? "" : display));
return this;
}
SyncFields secret(String label, String value) {
String v = value == null ? "" : value;
return put(label, v, v.isEmpty() ? "" : "••••••");
}
SyncFields flag(String label, boolean value) {
return put(label, value ? "Yes" : "No");
}
Map<String, Value> values() {
return values;
}
String compare(String label) {
Value v = values.get(label);
return v == null ? "" : v.compare();
}
String display(String label) {
Value v = values.get(label);
return v == null ? "" : v.display();
}
/** The labels whose values differ from {@code other}'s. */
Set<String> changedFrom(SyncFields other) {
Set<String> out = new LinkedHashSet<>();
for (String label : values.keySet()) {
if (other == null || !compare(label).equals(other.compare(label))) out.add(label);
}
return out;
}
boolean sameAs(SyncFields other) {
return changedFrom(other).isEmpty();
}
}
@@ -0,0 +1,429 @@
package eu.lixko.ts3j.client.myts;
import com.github.manevolent.ts3j.identity.LocalIdentity;
import eu.lixko.ts3j.client.config.Bookmark;
import eu.lixko.ts3j.client.config.Bookmarks;
import eu.lixko.ts3j.client.config.IdentityEntry;
import eu.lixko.ts3j.client.config.IdentityStore;
import eu.lixko.ts3j.client.config.Settings;
import eu.lixko.ts3j.client.proto.ProtobufMessage;
import eu.lixko.ts3j.client.teamspeak.SyncItem;
import eu.lixko.ts3j.client.teamspeak.SyncItemDecoder;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* One class of synchronised items and its local store: how both sides read as {@link SyncFields},
* how a local item is written into an {@code Item_Data}, and how a cloud item lands here.
*/
abstract sealed class SyncKind {
/** How identities are referred to across the two sides; bookmarks need it. */
static final class Links {
/** Cloud identity item UUID by local identity id. */
final Map<String, String> uuidByLocal = new HashMap<>();
/** Local identity id by cloud identity item UUID. */
final Map<String, String> localByUuid = new HashMap<>();
/** The cloud's identities by item UUID and by name, as bookmarks may use either. */
final Map<String, SyncItem.Identity> cloudIdentities = new HashMap<>();
/** Adds an identity the cloud holds; the first one added under a UUID or name stays. */
void addCloudIdentity(SyncItem.Identity identity) {
cloudIdentities.putIfAbsent(identity.uuid(), identity);
if (!identity.name().isEmpty()) cloudIdentities.putIfAbsent(identity.name(), identity);
}
}
final IdentityStore identities;
final Bookmarks bookmarks;
final Settings settings;
final Links links;
SyncKind(IdentityStore identities, Bookmarks bookmarks, Settings settings, Links links) {
this.identities = identities;
this.bookmarks = bookmarks;
this.settings = settings;
this.links = links;
}
abstract int itemClass();
/** The {@code Item_Data} field holding the content. */
abstract int contentField();
abstract List<String> localIds();
/** {@code null} when the item is gone. */
abstract SyncFields localFields(String localId);
/** {@code null} when the item is not of this kind or cannot be read. */
abstract SyncFields cloudFields(SyncItem item);
/** What makes a local and a cloud item the same one when neither knows of the other yet. */
abstract String matchKey(SyncFields fields);
abstract String title(SyncFields fields);
/** Whether the local store holds at most one item per {@link #matchKey}. */
boolean onePerKey() {
return false;
}
/** The UUID of the account's identity the item connects with, or {@code null}. */
String identityUsed(byte[] data) {
return null;
}
/** Whether all that differs from {@code base} is the identity, gone here. */
boolean lostIdentityOnly(SyncFields local, SyncFields base) {
return false;
}
/** Writes the labelled fields of the local item into the content message. */
abstract void write(String localId, ProtobufMessage content, Set<String> labels) throws IOException;
/** Writes what only an item new to the account carries, after {@link #write}. */
void writeNew(String localId, ProtobufMessage content) {
}
/** Creates the cloud item here; returns its local id. */
abstract String add(SyncItem cloud) throws IOException;
/** Makes the local item what the cloud holds; returns its local id, which may change. */
abstract String update(String localId, SyncItem cloud) throws IOException;
abstract void remove(String localId);
static final class IdentityKind extends SyncKind {
static final String NAME = "Name";
static final String NICKNAME = "Nickname";
static final String PHONETIC = "Phonetic nickname";
static final String KEY = "Unique ID";
IdentityKind(IdentityStore identities, Bookmarks bookmarks, Settings settings, Links links) {
super(identities, bookmarks, settings, links);
}
@Override
int itemClass() {
return 1;
}
@Override
int contentField() {
return 17;
}
@Override
List<String> localIds() {
return identities.all().stream().map(IdentityEntry::getId).collect(Collectors.toList());
}
@Override
SyncFields localFields(String localId) {
IdentityEntry e = identities.byId(localId);
if (e == null) return null;
return fields(e.getName(), e.getNickname(), e.getPhoneticNickname(), e.getIdentity());
}
@Override
SyncFields cloudFields(SyncItem item) {
if (!(item instanceof SyncItem.Identity i)) return null;
try {
return fields(i.name(), i.nickname(), i.phoneticNickname(),
IdentityStore.parseIdentityString(i.identity()));
} catch (IOException malformed) {
return null;
}
}
/**
* Which identity is the default is each installation's own: it is not compared, and travels
* only with an identity new to the other side, which takes it when it has no default yet.
*/
private static SyncFields fields(String name, String nickname, String phonetic, LocalIdentity key) {
String uid = key.getUid().toBase64();
return new SyncFields().put(NAME, name).put(NICKNAME, nickname).put(PHONETIC, phonetic)
.put(KEY, uid + "#" + key.getKeyOffset(), uid + " (level " + key.getSecurityLevel() + ")");
}
@Override
String matchKey(SyncFields fields) {
String key = fields.compare(KEY);
return key.substring(0, key.indexOf('#'));
}
@Override
String title(SyncFields fields) {
return fields.display(NAME);
}
/** Adding an identity whose key is here already updates that one instead. */
@Override
boolean onePerKey() {
return true;
}
@Override
void write(String localId, ProtobufMessage content, Set<String> labels) throws IOException {
IdentityEntry e = identities.byId(localId);
if (labels.contains(KEY)) content.string(1, IdentityStore.identityString(e.getIdentity()));
if (labels.contains(NAME)) content.string(2, e.getName());
if (labels.contains(NICKNAME)) content.string(3, e.getNickname());
if (labels.contains(PHONETIC)) content.string(4, e.getPhoneticNickname());
}
/** The account's default only when it has none: another installation's default stays. */
@Override
void writeNew(String localId, ProtobufMessage content) {
boolean cloudHasDefault = links.cloudIdentities.values().stream().anyMatch(SyncItem.Identity::isDefault);
content.varint(5, !cloudHasDefault && localId.equals(settings.defaultIdentityId.get()) ? 1 : 0);
}
@Override
String add(SyncItem cloud) throws IOException {
SyncItem.Identity i = (SyncItem.Identity) cloud;
LocalIdentity key = IdentityStore.parseIdentityString(i.identity());
IdentityEntry existing = identities.byUniqueId(key.getUid().toBase64());
if (existing != null) return update(existing.getId(), cloud);
String name = i.name().isBlank() ? (i.nickname().isBlank() ? "TeamSpeak identity" : i.nickname()) : i.name();
IdentityEntry e = identities.add(name, key, i.nickname(), i.phoneticNickname());
if (i.isDefault() && identities.byId(settings.defaultIdentityId.get()) == null) {
settings.defaultIdentityId.set(e.getId());
}
return e.getId();
}
@Override
String update(String localId, SyncItem cloud) throws IOException {
SyncItem.Identity i = (SyncItem.Identity) cloud;
IdentityEntry e = identities.byId(localId);
if (e == null) return add(cloud);
LocalIdentity key = IdentityStore.parseIdentityString(i.identity());
if (!key.getUid().toBase64().equals(e.getUniqueId())) {
// Another key altogether: a new identity takes the old one's place.
List<Bookmark> using = new ArrayList<>();
for (Bookmark b : bookmarks.all()) {
if (localId.equals(b.identityId)) using.add(b);
}
boolean wasDefault = localId.equals(settings.defaultIdentityId.get());
IdentityEntry replacement = identities.add(i.name().isBlank() ? e.getName() : i.name(), key,
i.nickname(), i.phoneticNickname());
identities.remove(e, settings, null);
for (Bookmark b : using) b.identityId = replacement.getId();
if (wasDefault) settings.defaultIdentityId.set(replacement.getId());
return replacement.getId();
}
if (key.getKeyOffset() != e.getIdentity().getKeyOffset()) identities.setKeyOffset(e, key);
if (!i.name().isBlank() && !i.name().equals(e.getName())) identities.rename(e, i.name());
if (!i.nickname().equals(e.getNickname()) || !i.phoneticNickname().equals(e.getPhoneticNickname())) {
identities.setNicknames(e, i.nickname(), i.phoneticNickname());
}
return localId;
}
@Override
void remove(String localId) {
IdentityEntry e = identities.byId(localId);
if (e != null) identities.remove(e, settings, bookmarks);
}
}
static final class BookmarkKind extends SyncKind {
static final String NAME = "Name";
static final String ADDRESS = "Address";
static final String NICKNAME = "Nickname";
static final String PASSWORD = "Server password";
static final String IDENTITY = "Identity";
static final String CHANNEL = "Default channel";
static final String CHANNEL_PASSWORD = "Channel password";
static final String AUTOCONNECT = "Connect on startup";
static final String MYTS = "myTeamSpeak features";
private static final Pattern CHANNEL_ID = Pattern.compile("/(\\d+)");
BookmarkKind(IdentityStore identities, Bookmarks bookmarks, Settings settings, Links links) {
super(identities, bookmarks, settings, links);
}
@Override
int itemClass() {
return 0;
}
@Override
int contentField() {
return 16;
}
@Override
List<String> localIds() {
return bookmarks.all().stream().map(b -> b.id).collect(Collectors.toList());
}
@Override
SyncFields localFields(String localId) {
Bookmark b = bookmarks.find(localId);
if (b == null) return null;
IdentityEntry identity = b.identityId == null || b.identityId.isBlank() ? null : identities.byId(b.identityId);
return fields(b.label, b.address, b.port, b.nickname,
identity == null ? "" : identity.getUniqueId(), identity == null ? "Default" : identity.getName(),
b.password, b.channel, b.channelPassword, b.connectOnStartup, b.myTeamSpeakFeatures);
}
@Override
SyncFields cloudFields(SyncItem item) {
if (!(item instanceof SyncItem.Bookmark b)) return null;
// One the cloud does not hold connects with the default, as it does once brought here.
SyncItem.Identity identity = b.identityUuid().isEmpty() ? null : links.cloudIdentities.get(b.identityUuid());
String uid = "", name = "Default";
if (identity != null) {
name = identity.name();
try {
uid = IdentityStore.parseIdentityString(identity.identity()).getUid().toBase64();
} catch (IOException malformed) {
uid = "?" + identity.uuid();
}
}
return fields(b.name(), b.address(), b.port(), b.nickname(), uid, name, b.serverPassword(), channelOf(b),
b.defaultChannelPassword(), b.autoconnect(), b.myTeamSpeakFeatures());
}
private static SyncFields fields(String label, String address, int port, String nickname, String identityUid,
String identityName, String password, String channel, String channelPassword,
boolean autoconnect, boolean myts) {
String hostPort = Bookmark.hostPort(address == null ? "" : address.trim(), port);
return new SyncFields().put(NAME, label).put(ADDRESS, hostPort.toLowerCase(java.util.Locale.ROOT), hostPort)
.put(NICKNAME, nickname).put(IDENTITY, identityUid, identityName).secret(PASSWORD, password).put(CHANNEL, channel)
.secret(CHANNEL_PASSWORD, channelPassword).flag(AUTOCONNECT, autoconnect).flag(MYTS, myts);
}
private static String channelOf(SyncItem.Bookmark b) {
if (b.defaultChannel().isBlank() && b.defaultChannelId() != 0) return "/" + b.defaultChannelId();
return b.defaultChannel();
}
@Override
String matchKey(SyncFields fields) {
return fields.compare(NAME) + "\n" + fields.compare(ADDRESS);
}
@Override
String title(SyncFields fields) {
String name = fields.display(NAME);
return name.isBlank() ? fields.display(ADDRESS) : name;
}
@Override
String identityUsed(byte[] data) {
SyncItem.Identity identity = null;
try {
if (SyncItemDecoder.decode(data) instanceof SyncItem.Bookmark b && !b.identityUuid().isEmpty()) {
identity = links.cloudIdentities.get(b.identityUuid());
}
} catch (IOException | RuntimeException unreadable) {
return null;
}
return identity == null ? null : identity.uuid();
}
@Override
boolean lostIdentityOnly(SyncFields local, SyncFields base) {
return local.compare(IDENTITY).isEmpty() && local.changedFrom(base).equals(Set.of(IDENTITY));
}
@Override
void write(String localId, ProtobufMessage content, Set<String> labels) {
Bookmark b = bookmarks.find(localId);
if (labels.contains(NAME)) content.string(1, nonNull(b.label));
if (labels.contains(ADDRESS)) {
content.string(2, nonNull(b.address).trim());
content.varint(3, b.port);
}
if (labels.contains(NICKNAME)) content.string(4, nonNull(b.nickname));
if (labels.contains(IDENTITY)) {
String uuid = b.identityId == null ? null : links.uuidByLocal.get(b.identityId);
content.string(6, uuid == null ? "" : uuid);
}
if (labels.contains(PASSWORD)) content.string(7, nonNull(b.password));
if (labels.contains(CHANNEL)) {
String channel = nonNull(b.channel);
Matcher id = CHANNEL_ID.matcher(channel);
if (id.matches()) {
content.string(8, "");
content.varint(10, Long.parseLong(id.group(1)));
} else {
content.string(8, channel);
content.varint(10, 0);
}
}
if (labels.contains(CHANNEL_PASSWORD)) content.string(9, nonNull(b.channelPassword));
if (labels.contains(AUTOCONNECT)) content.varint(14, b.connectOnStartup ? 1 : 0);
if (labels.contains(MYTS)) content.varint(22, b.myTeamSpeakFeatures ? 1 : 0);
}
@Override
String add(SyncItem cloud) {
Bookmark b = new Bookmark();
if (bookmarks.find(cloud.uuid()) == null) b.id = cloud.uuid();
copy((SyncItem.Bookmark) cloud, b);
bookmarks.add(b);
return b.id;
}
@Override
String update(String localId, SyncItem cloud) {
Bookmark b = bookmarks.find(localId);
if (b == null) return add(cloud);
copy((SyncItem.Bookmark) cloud, b);
return localId;
}
/** Everything that synchronises; what only this client keeps, like whisper controls, stays. */
private void copy(SyncItem.Bookmark from, Bookmark to) {
to.label = from.name();
to.address = from.address();
to.port = from.port();
to.nickname = from.nickname();
to.password = from.serverPassword();
to.channel = channelOf(from);
to.channelPassword = from.defaultChannelPassword();
to.connectOnStartup = from.autoconnect();
to.myTeamSpeakFeatures = from.myTeamSpeakFeatures();
to.identityId = "";
if (from.identityUuid().isEmpty()) return;
SyncItem.Identity identity = links.cloudIdentities.get(from.identityUuid());
if (identity == null) return;
String local = links.localByUuid.get(identity.uuid());
if (local == null || local.isEmpty()) {
// An account item not synchronised on its own, as a second copy of a key is not.
try {
IdentityEntry same = identities.byUniqueId(
IdentityStore.parseIdentityString(identity.identity()).getUid().toBase64());
local = same == null ? null : same.getId();
} catch (IOException malformed) {
local = null;
}
}
if (local != null) to.identityId = local;
}
@Override
void remove(String localId) {
Bookmark b = bookmarks.find(localId);
if (b != null) bookmarks.all().remove(b);
}
private static String nonNull(String s) {
return s == null ? "" : s;
}
}
}
@@ -0,0 +1,87 @@
package eu.lixko.ts3j.client.myts;
import eu.lixko.ts3j.client.config.ProfileFiles;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
/**
* What the account held after the last synchronisation, which tells a change made here
* from one made elsewhere: each class's cursor, and each synchronised item with the
* revision it had, its contents and the bookmark or identity it is here. Holds identity
* keys, so it lives in the private profile like they do.
*/
final class SyncState {
static final String FILE_NAME = "myteamspeak-sync.properties";
/**
* @param localId the {@link eu.lixko.ts3j.client.config.Bookmark#id} or
* {@link eu.lixko.ts3j.client.config.IdentityEntry#getId()} the item is here
*/
record Entry(int itemClass, String uuid, String version, String localId, byte[] data) {
}
String global = MyTeamSpeak.NO_VERSION;
final Map<Integer, String> cursors = new TreeMap<>();
final Map<String, Entry> items = new LinkedHashMap<>();
/** The state kept for {@code account}; empty when there is none or it is another account's. */
static SyncState load(File file, String account) {
SyncState state = new SyncState();
if (!file.isFile()) return state;
Properties p = new Properties();
try (InputStream in = new FileInputStream(file)) {
p.load(in);
} catch (IOException unreadable) {
return state;
}
if (!account.equalsIgnoreCase(p.getProperty("account", ""))) return state;
try {
state.global = p.getProperty("global", MyTeamSpeak.NO_VERSION);
for (String key : p.stringPropertyNames()) {
if (key.startsWith("cursor.")) {
state.cursors.put(Integer.parseInt(key.substring("cursor.".length())), p.getProperty(key));
}
}
int count = Integer.parseInt(p.getProperty("items", "0"));
for (int i = 0; i < count; i++) {
String prefix = "item." + i + ".";
Entry entry = new Entry(Integer.parseInt(p.getProperty(prefix + "class")),
p.getProperty(prefix + "uuid"), p.getProperty(prefix + "version"),
p.getProperty(prefix + "local", ""),
Base64.getDecoder().decode(p.getProperty(prefix + "data")));
state.items.put(entry.uuid(), entry);
}
} catch (RuntimeException corrupt) {
// Starts over: the next synchronisation matches items up again, as the first one does.
return new SyncState();
}
return state;
}
void save(File file, String account) throws IOException {
Properties p = new Properties();
p.setProperty("account", account);
p.setProperty("global", global);
cursors.forEach((itemClass, cursor) -> p.setProperty("cursor." + itemClass, cursor));
p.setProperty("items", Integer.toString(items.size()));
int i = 0;
for (Entry entry : items.values()) {
String prefix = "item." + i++ + ".";
p.setProperty(prefix + "class", Integer.toString(entry.itemClass()));
p.setProperty(prefix + "uuid", entry.uuid());
p.setProperty(prefix + "version", entry.version());
p.setProperty(prefix + "local", entry.localId());
p.setProperty(prefix + "data", Base64.getEncoder().encodeToString(entry.data()));
}
ProfileFiles.write(file, out -> p.store(out, "myTeamSpeak synchronisation state"));
}
}
@@ -0,0 +1,113 @@
package eu.lixko.ts3j.client.net;
import eu.lixko.ts3j.client.sound.SoundEvent;
import eu.lixko.ts3j.client.sound.SoundNotifier;
import eu.lixko.ts3j.client.text.TsLink;
import java.util.Map;
import java.util.function.BooleanSupplier;
/**
* Tells the user what happens on a connection the way TeamSpeak does: a line in the server
* tab's log, with the channels and clients in it linked, and the sound pack's entry, with
* the names it may speak.
*/
final class Announcer {
private final ServerModel model;
private final SoundNotifier sounds;
private final ConnectionListener ui;
private final ChatLog chatLog;
/** Speakers muted: only actions marked important are still heard. */
private final BooleanSupplier deafened;
private final BooleanSupplier connected;
Announcer(ServerModel model, SoundNotifier sounds, ConnectionListener ui, ChatLog chatLog,
BooleanSupplier deafened, BooleanSupplier connected) {
this.model = model;
this.sounds = sounds;
this.ui = ui;
this.chatLog = chatLog;
this.deafened = deafened;
this.connected = connected;
}
/** Plays the sound pack's entry for an action. */
void sound(SoundEvent event) {
sounds.fire(event, deafened.getAsBoolean());
}
void sound(SoundEvent event, Map<String, String> variables) {
sounds.fire(event, deafened.getAsBoolean(), variables);
}
/** Records a line in the server tab's log; nothing once the connection is gone. */
void log(String message) {
if (connected.getAsBoolean()) chatLog.serverEvent(message);
}
/** Reports a failure to the UI and plays the matching server sound. */
void error(String prefix, Exception e) {
sound(RequestException.isPermissionError(e)
? SoundEvent.SERVER_INSUFFICIENT_PERMISSIONS
: SoundEvent.SERVER_ERROR, serverVars());
ui.onError(prefix + RequestException.rootMessage(e));
}
String channelName(int channelId) {
ChannelNode ch = model.getChannel(channelId);
return ch != null ? ch.name : "channel #" + channelId;
}
/**
* A channel's name as the log wants it: TeamSpeak's own {@code channel://} link, which
* the chat log turns into the same clickable entry a dragged-in channel produces. A
* channel we no longer know (a deleted one, say) is named in plain text instead.
*/
String channelLink(int channelId) {
ChannelNode ch = model.getChannel(channelId);
return ch != null ? TsLink.channelBBCode(channelId, ch.name) : channelName(channelId);
}
/** The same for a client, named by the model. */
String clientLink(int clientId) {
ClientEntry c = model.getClient(clientId);
return c != null ? clientLink(clientId, c.uniqueId, c.nickname) : "Client " + clientId;
}
/** The same for a client an event describes, which may already be gone from the model. */
String clientLink(int clientId, String uniqueId, String nickname) {
if (clientId <= 0 || nickname == null || nickname.isEmpty()) return orEmpty(nickname);
return TsLink.clientBBCode(clientId, orEmpty(uniqueId), nickname);
}
/** The placeholder values a pack may reference for an action involving a client. */
Map<String, String> clientVars(int clientId, String fallbackName) {
ClientEntry c = model.getClient(clientId);
Map<String, String> vars = SoundNotifier.vars(
"servername", model.getServerName(),
"clientname", c != null ? c.nickname : orEmpty(fallbackName),
"clientuid", c != null ? c.uniqueId : "");
if (c != null) {
ChannelNode ch = model.getChannel(c.channelId);
if (ch != null) vars.put("channelname", ch.name);
}
return vars;
}
Map<String, String> channelVars(int channelId, String invokerName) {
ChannelNode ch = model.getChannel(channelId);
return SoundNotifier.vars(
"servername", model.getServerName(),
"channelname", ch != null ? ch.name : "",
"clientname", orEmpty(invokerName));
}
Map<String, String> serverVars() {
return SoundNotifier.vars("servername", model.getServerName());
}
private static String orEmpty(String s) {
return s == null ? "" : s;
}
}
@@ -4,60 +4,92 @@ import com.github.manevolent.ts3j.command.SingleCommand;
import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter; import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter;
import com.github.manevolent.ts3j.protocol.ProtocolRole; import com.github.manevolent.ts3j.protocol.ProtocolRole;
import eu.lixko.ts3j.client.net.avatar.AvatarNaming; import eu.lixko.ts3j.client.net.avatar.AvatarNaming;
import eu.lixko.ts3j.client.net.avatar.AvatarRepository;
import eu.lixko.ts3j.client.net.avatar.ImageFormat; import eu.lixko.ts3j.client.net.avatar.ImageFormat;
import eu.lixko.ts3j.client.net.filetransfer.FileTransfer; import eu.lixko.ts3j.client.net.filetransfer.FileTransfer;
import eu.lixko.ts3j.client.net.filetransfer.FileTransferManager;
import java.io.File; import java.io.File;
import java.nio.file.Files; import java.nio.file.Files;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Supplier;
/** /**
* Publishes and withdraws the local client's avatar, the way the official client does * Publishes and withdraws the local client's avatar, the way the official client does
* it: the picture goes into channel 0's file repository as {@code /avatar_<name>} and * it: the picture goes into channel 0's file repository as {@code /avatar_<name>} and
* {@code client_flag_avatar} is then set to its MD5, which is what other clients key * {@code client_flag_avatar} is then set to its MD5, which is what other clients key
* their downloads on. * their downloads on.
*
* <p>Requests run in the background and fail with a {@link RequestException}.
*/ */
final class AvatarAdmin { public final class AvatarAdmin {
/** The server's own default for {@code i_client_max_avatar_filesize}. */
static final int DEFAULT_MAX_AVATAR_BYTES = 200_000;
/** The largest avatar we are willing to download, whatever a server allows. */ /** The largest avatar we are willing to download, whatever a server allows. */
static final int MAX_AVATAR_DOWNLOAD_BYTES = 8 * 1024 * 1024; static final int MAX_AVATAR_DOWNLOAD_BYTES = 8 * 1024 * 1024;
private static final long UPLOAD_TIMEOUT_MS = 60_000; private static final long UPLOAD_TIMEOUT_MS = 60_000;
private final TeamspeakConnection conn; private final Uplink uplink;
private final Permissions permissions;
private final AvatarRepository avatars;
/** Our unique id, which names our avatar file. */
private final Supplier<String> selfUniqueId;
/** Shows our new avatar flag on our own entry; the server tells only the other clients. */
private final Consumer<String> ownFlagChanged;
AvatarAdmin(TeamspeakConnection conn) { AvatarAdmin(Uplink uplink, Permissions permissions, AvatarRepository avatars,
this.conn = conn; Supplier<String> selfUniqueId, Consumer<String> ownFlagChanged) {
this.uplink = uplink;
this.permissions = permissions;
this.avatars = avatars;
this.selfUniqueId = selfUniqueId;
this.ownFlagChanged = ownFlagChanged;
}
/** Uploads an image as our avatar and publishes it to the other clients. */
public CompletableFuture<Void> set(File source) {
return uplink.requestVoid(() -> ownFlagChanged.accept(upload(source)));
}
/** Withdraws our avatar. */
public CompletableFuture<Void> remove() {
return uplink.requestVoid(() -> {
setFlag("");
ownFlagChanged.accept("");
try {
deleteFile(selfUniqueId.get());
} catch (Exception ignored) {
// The flag is what other clients go by; a leftover file only wastes space.
// Servers refuse the deletion unless we may delete others' avatars too.
}
});
} }
/** /**
* How large an avatar this server lets us upload, from * Deletes another client's avatar, which needs {@code b_client_avatar_delete_other};
* {@code i_client_max_avatar_filesize}, or the server default while unknown. * the server then clears their flag for everyone.
*/ */
int maxUploadBytes() { public CompletableFuture<Void> removeOf(ClientEntry client) {
int limit = conn.getModel().selfPermissionValue("i_client_max_avatar_filesize"); return uplink.requestVoid(() -> deleteFile(client.uniqueId));
return limit > 0 ? limit : DEFAULT_MAX_AVATAR_BYTES;
} }
/** Uploads {@code source} as our avatar and announces it; returns its flag. */ /** Uploads {@code source} as our avatar and announces it; returns its flag. */
String upload(File source) throws Exception { private String upload(File source) throws Exception {
byte[] data = Files.readAllBytes(source.toPath()); byte[] data = Files.readAllBytes(source.toPath());
if (data.length == 0) throw new IllegalArgumentException("That file is empty"); if (data.length == 0) throw new IllegalArgumentException("That file is empty");
if (ImageFormat.detect(data) == null) { if (ImageFormat.detect(data) == null) {
throw new IllegalArgumentException("Avatars must be PNG, JPEG, GIF or BMP images"); throw new IllegalArgumentException("Avatars must be PNG, JPEG, GIF or BMP images");
} }
int limit = maxUploadBytes(); int limit = permissions.maxAvatarBytes();
if (data.length > limit) { if (data.length > limit) {
throw new IllegalArgumentException("This server limits avatars to " + (limit / 1024) + " KiB"); throw new IllegalArgumentException("This server limits avatars to " + (limit / 1024) + " KiB");
} }
String name = ownFileName(); String name = ownFileName();
CountDownLatch done = new CountDownLatch(1); CountDownLatch done = new CountDownLatch(1);
FileTransfer transfer = fileTransfers().upload(0, "", "/" + name, source, true, t -> { FileTransfer transfer = uplink.files().upload(0, "", "/" + name, source, true, t -> {
if (t.isDone()) done.countDown(); if (t.isDone()) done.countDown();
}); });
if (!done.await(UPLOAD_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { if (!done.await(UPLOAD_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
@@ -69,52 +101,27 @@ final class AvatarAdmin {
} }
String flag = AvatarNaming.flag(data); String flag = AvatarNaming.flag(data);
setFlag(flag); setFlag(flag);
conn.getAvatars().put(data); avatars.put(data);
return flag; return flag;
} }
/** Clears our avatar flag and removes the file from the server. */
void remove() throws Exception {
setFlag("");
try {
deleteFile(conn.getSelfUniqueId());
} catch (Exception ignored) {
// The flag is what other clients go by; a leftover file only wastes space.
// Servers refuse the deletion unless we may delete others' avatars too.
}
}
/**
* Deletes another client's avatar, which needs {@code b_client_avatar_delete_other};
* the server then clears their flag for everyone.
*/
void removeOther(String uniqueId) throws Exception {
deleteFile(uniqueId);
}
/** /**
* Deleting names the avatar by its owner's unique id, {@code /avatar_<uid>}, which the * Deleting names the avatar by its owner's unique id, {@code /avatar_<uid>}, which the
* server maps to the stored file itself; the stored name is refused ("convert error"). * server maps to the stored file itself; the stored name is refused ("convert error").
*/ */
private void deleteFile(String uniqueId) throws Exception { private void deleteFile(String uniqueId) throws Exception {
fileTransfers().delete(0, "", "/avatar_" + uniqueId); uplink.files().delete(0, "", "/avatar_" + uniqueId);
} }
private void setFlag(String flag) throws Exception { private void setFlag(String flag) throws Exception {
SingleCommand cmd = new SingleCommand("clientupdate", ProtocolRole.CLIENT, SingleCommand cmd = new SingleCommand("clientupdate", ProtocolRole.CLIENT,
new CommandSingleParameter("client_flag_avatar", flag)); new CommandSingleParameter("client_flag_avatar", flag));
conn.socket().executeCommand(cmd).complete(); uplink.socket().executeCommand(cmd).complete();
} }
private String ownFileName() { private String ownFileName() {
String name = AvatarNaming.fileName(conn.getSelfUniqueId()); String name = AvatarNaming.fileName(selfUniqueId.get());
if (name == null) throw new IllegalStateException("Our identity has no usable unique id"); if (name == null) throw new IllegalStateException("Our identity has no usable unique id");
return name; return name;
} }
private FileTransferManager fileTransfers() {
FileTransferManager ft = conn.fileTransfers();
if (ft == null) throw new IllegalStateException("Not connected");
return ft;
}
} }
@@ -9,24 +9,22 @@ import eu.lixko.ts3j.client.net.ban.BanEntry;
import eu.lixko.ts3j.client.net.ban.BanRule; import eu.lixko.ts3j.client.net.ban.BanRule;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.concurrent.CompletableFuture;
/** /**
* The server's ban list: reading it and adding, replacing and deleting entries. * The server's ban list: reading it and adding, replacing and deleting entries.
* *
* <p>Split out of {@link TeamspeakConnection} like {@link ChannelAdmin}, and for the same * <p>Requests run in the background and fail with a {@link RequestException}.
* reason: it is a self-contained request/response corner of the protocol that only the
* ban list window uses. Every call here blocks and must run off the UI thread; the
* connection's public wrappers do that.
*/ */
final class BanAdmin { public final class BanAdmin {
/** What {@code banlist} answers when there are no bans at all. */ /** What {@code banlist} answers when there are no bans at all. */
private static final int ERROR_DATABASE_EMPTY_RESULT = 0x0501; private static final int ERROR_DATABASE_EMPTY_RESULT = 0x0501;
private final TeamspeakConnection conn; private final Uplink uplink;
/** /**
* The {@code banlist} reply in progress. The server answers the command with a burst * The {@code banlist} reply in progress. The server answers the command with a burst
@@ -36,19 +34,51 @@ final class BanAdmin {
*/ */
private volatile List<BanEntry> listing; private volatile List<BanEntry> listing;
BanAdmin(TeamspeakConnection conn) { BanAdmin(Uplink uplink) {
this.conn = conn; this.uplink = uplink;
} }
/** Reads every ban on the server. */ /** Reads every ban on the server. */
List<BanEntry> list() throws Exception { public CompletableFuture<List<BanEntry>> list() {
return uplink.request(this::readList);
}
public CompletableFuture<Void> add(BanRule rule) {
return uplink.requestVoid(() -> addNow(rule));
}
/**
* Replaces a ban with a re-written one. The server has no way to edit a ban in place,
* so the new one is added before the old is removed: a failure half-way leaves the
* client banned twice rather than not at all.
*/
public CompletableFuture<Void> replace(int banId, BanRule rule) {
return uplink.requestVoid(() -> {
addNow(rule);
try {
deleteNow(banId);
} catch (Exception e) {
throw new IllegalStateException("The edited ban was added, but the original could not be"
+ " removed: " + e.getMessage(), e);
}
});
}
/** Deletes bans one by one, stopping at the first the server refuses. */
public CompletableFuture<Void> delete(Collection<Integer> banIds) {
return uplink.requestVoid(() -> {
for (int id : banIds) deleteNow(id);
});
}
private List<BanEntry> readList() throws Exception {
List<BanEntry> entries = Collections.synchronizedList(new ArrayList<>()); List<BanEntry> entries = Collections.synchronizedList(new ArrayList<>());
listing = entries; listing = entries;
try { try {
conn.socket().executeCommand(new SingleCommand("banlist", ProtocolRole.CLIENT)).complete(); uplink.socket().executeCommand(new SingleCommand("banlist", ProtocolRole.CLIENT)).complete();
// The entries were queued on the event thread before the command's own reply // The entries were queued on the event thread before the command's own reply
// was read, so draining that thread is what guarantees they have all landed. // was read, so draining that thread is what guarantees they have all landed.
conn.awaitEventsProcessed(); uplink.awaitEventsProcessed();
} catch (CommandException e) { } catch (CommandException e) {
if (e.getErrorId() != ERROR_DATABASE_EMPTY_RESULT) throw e; if (e.getErrorId() != ERROR_DATABASE_EMPTY_RESULT) throw e;
} finally { } finally {
@@ -65,12 +95,7 @@ final class BanAdmin {
if (entry.id >= 0) entries.add(entry); if (entry.id >= 0) entries.add(entry);
} }
/** private void addNow(BanRule rule) throws Exception {
* Adds a ban.
*
* @return the new ban's id, or -1 where the server did not name it
*/
int add(BanRule rule) throws Exception {
if (!rule.hasTarget()) throw new IllegalArgumentException("A ban needs something to match"); if (!rule.hasTarget()) throw new IllegalArgumentException("A ban needs something to match");
SingleCommand cmd = new SingleCommand("banadd", ProtocolRole.CLIENT); SingleCommand cmd = new SingleCommand("banadd", ProtocolRole.CLIENT);
addIfSet(cmd, "ip", rule.ipRegex); addIfSet(cmd, "ip", rule.ipRegex);
@@ -79,34 +104,13 @@ final class BanAdmin {
addIfSet(cmd, "mytsid", rule.mytsid); addIfSet(cmd, "mytsid", rule.mytsid);
if (!rule.isPermanent()) cmd.add(new CommandSingleParameter("time", Long.toString(rule.durationSeconds))); if (!rule.isPermanent()) cmd.add(new CommandSingleParameter("time", Long.toString(rule.durationSeconds)));
addIfSet(cmd, "banreason", rule.reason); addIfSet(cmd, "banreason", rule.reason);
for (SingleCommand answer : conn.socket().executeCommand(cmd).get()) { uplink.socket().executeCommand(cmd).complete();
Map<String, String> fields = answer.toMap();
if (fields.containsKey("banid")) {
return BanEntry.from(fields).id;
}
}
return -1;
} }
/** private void deleteNow(int banId) throws Exception {
* Replaces a ban with a re-written one. The server has no way to edit a ban in place,
* so the new one is added before the old is removed: a failure half-way leaves the
* client banned twice rather than not at all.
*/
void replace(int banId, BanRule rule) throws Exception {
add(rule);
try {
delete(banId);
} catch (Exception e) {
throw new IllegalStateException("The edited ban was added, but the original could not be"
+ " removed: " + e.getMessage(), e);
}
}
void delete(int banId) throws Exception {
SingleCommand cmd = new SingleCommand("bandel", ProtocolRole.CLIENT, SingleCommand cmd = new SingleCommand("bandel", ProtocolRole.CLIENT,
new CommandSingleParameter("banid", Integer.toString(banId))); new CommandSingleParameter("banid", Integer.toString(banId)));
conn.socket().executeCommand(cmd).complete(); uplink.socket().executeCommand(cmd).complete();
} }
private static void addIfSet(SingleCommand cmd, String key, String value) { private static void addIfSet(SingleCommand cmd, String key, String value) {
@@ -7,7 +7,6 @@ import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter;
import com.github.manevolent.ts3j.event.UnknownTeamspeakEvent; import com.github.manevolent.ts3j.event.UnknownTeamspeakEvent;
import com.github.manevolent.ts3j.protocol.ProtocolRole; import com.github.manevolent.ts3j.protocol.ProtocolRole;
import eu.lixko.ts3j.client.net.filetransfer.FileTransfer; import eu.lixko.ts3j.client.net.filetransfer.FileTransfer;
import eu.lixko.ts3j.client.net.filetransfer.FileTransferManager;
import eu.lixko.ts3j.client.net.filetransfer.RemoteFile; import eu.lixko.ts3j.client.net.filetransfer.RemoteFile;
import java.io.File; import java.io.File;
@@ -17,20 +16,21 @@ import java.util.Collection;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.zip.CRC32; import java.util.zip.CRC32;
/** /**
* Everything the channel editor needs of the server: reading and writing a channel's * What we do with channels: joining, moving and subscribing to them, and what the channel
* properties and its needed-power permissions, plus the virtual server's icon store. * editor needs of the server: reading and writing a channel's properties and its
* needed-power permissions, plus the virtual server's icon store.
* *
* <p>Split out of {@link TeamspeakConnection} because it is a self-contained request/ * <p>Requests run in the background and fail with a {@link RequestException}; the actions
* response corner of the protocol that only the editor uses. Every call here blocks and * that return nothing report a failure in the log.
* must run off the UI thread; the connection's public wrappers do that.
*/ */
final class ChannelAdmin { public final class ChannelAdmin {
/** The directory a server's icons live in, where the server has one. */ /** The directory a server's icons live in, where the server has one. */
private static final String ICON_DIRECTORY = "icons"; private static final String ICON_DIRECTORY = "icons";
@@ -38,7 +38,9 @@ final class ChannelAdmin {
/** How long to wait for a whole icon to travel over the file connection. */ /** How long to wait for a whole icon to travel over the file connection. */
private static final long ICON_UPLOAD_TIMEOUT_MS = 30_000; private static final long ICON_UPLOAD_TIMEOUT_MS = 30_000;
private final TeamspeakConnection conn; private final Uplink uplink;
private final ServerModel model;
private final Announcer announce;
/** /**
* The {@code channelpermlist} reply in progress. TeamSpeak answers the command with a * The {@code channelpermlist} reply in progress. TeamSpeak answers the command with a
@@ -48,72 +50,192 @@ final class ChannelAdmin {
*/ */
private volatile PermRequest permRequest; private volatile PermRequest permRequest;
ChannelAdmin(TeamspeakConnection conn) { ChannelAdmin(Uplink uplink, ServerModel model, Announcer announce) {
this.conn = conn; this.uplink = uplink;
this.model = model;
this.announce = announce;
}
// ---- channel actions ----
/** @param password the channel's password, or null or empty when it has none */
public void join(int channelId, String password) {
act("Could not join channel: ", sock ->
sock.joinChannel(channelId, (password == null || password.isEmpty()) ? null : password));
}
/**
* Re-parents and repositions a channel.
*
* @param orderPredecessorId the channel this one should sit below among its new
* siblings, or 0 to place it first
*/
public void move(int channelId, int newParentId, int orderPredecessorId) {
ChannelNode channel = model.getChannel(channelId);
// The server refuses channelmove within the same parent ("already member of
// channel"); sorting among the same siblings is an edit of channel_order.
boolean reorder = channel != null && channel.parentId == newParentId;
act("Could not move channel: ", sock -> {
SingleCommand cmd;
if (reorder) {
cmd = new SingleCommand("channeledit", ProtocolRole.CLIENT);
cmd.add(new CommandSingleParameter("cid", Integer.toString(channelId)));
cmd.add(new CommandSingleParameter("channel_order", Integer.toString(orderPredecessorId)));
} else {
cmd = new SingleCommand("channelmove", ProtocolRole.CLIENT);
cmd.add(new CommandSingleParameter("cid", Integer.toString(channelId)));
cmd.add(new CommandSingleParameter("cpid", Integer.toString(newParentId)));
cmd.add(new CommandSingleParameter("order", Integer.toString(orderPredecessorId)));
}
sock.executeCommand(cmd).complete();
});
}
/**
* Subscribes to (or unsubscribes from) a set of channels in one command. The model
* is left alone: the server answers with the subscription events that update it.
*/
public void setSubscribed(Collection<Integer> channelIds, boolean subscribed) {
if (channelIds.isEmpty()) return;
List<Integer> ids = List.copyOf(channelIds);
String name = subscribed ? "channelsubscribe" : "channelunsubscribe";
act(subscribed ? "Could not subscribe: " : "Could not unsubscribe: ", sock -> {
List<SingleCommand> parts = new ArrayList<>(ids.size());
for (int id : ids) {
parts.add(new SingleCommand(name, ProtocolRole.CLIENT,
new CommandSingleParameter("cid", Integer.toString(id))));
}
sock.executeCommand(new MultiCommand(name, ProtocolRole.CLIENT, parts)).complete();
});
}
/**
* Asks for a channel's description. The answer arrives as a channel edit, see
* {@link ConnectionEventHandler#onChannelEdit}. Uses {@code channelgetdescription}, not
* {@code channelinfo}, which counts heavily against the server's flood protection. May
* be refused; the description then stays unknown.
*/
public void requestInfo(int channelId) {
uplink.submit(sock -> sock.executeCommand(new SingleCommand("channelgetdescription", ProtocolRole.CLIENT,
new CommandSingleParameter("cid", Integer.toString(channelId)))).complete(), e -> {
});
}
private void act(String errorPrefix, Uplink.Action action) {
uplink.submit(action, e -> announce.error(errorPrefix, e));
} }
// ---- channel properties ---- // ---- channel properties ----
/** Reads a channel's full property set. */ /** Reads a channel's full property set. */
ChannelSettings readSettings(int channelId) throws Exception { public CompletableFuture<ChannelSettings> settings(int channelId) {
Channel info = conn.socket().getChannelInfo(channelId); return uplink.request(() -> {
Channel info = uplink.socket().getChannelInfo(channelId);
if (info == null) throw new IllegalStateException("The server did not describe that channel"); if (info == null) throw new IllegalStateException("The server did not describe that channel");
return ChannelSettings.from(channelId, info.getMap()); return ChannelSettings.from(channelId, info.getMap());
});
} }
/** /**
* Creates a channel below {@code parentId} (0 being the top level). * Creates a channel below {@code parentId} (0 being the top level) and gives it the
* channel permissions it was created with.
* *
* @param properties the new channel's properties, as {@link ChannelSettings#creationParameters} * @param properties the new channel's properties, as {@link ChannelSettings#creationParameters}
* @return the new channel's id * @return the new channel's id. A channel whose permissions could not be set still
* exists, and fails the request with a message saying so.
*/ */
int create(int parentId, Map<String, String> properties) throws Exception { public CompletableFuture<Integer> create(int parentId, Map<String, String> properties,
Map<String, Integer> permissions) {
return uplink.request(() -> {
int channelId = createNow(parentId, properties);
try {
writePermissions(channelId, permissions, List.of());
} catch (Exception e) {
throw new IllegalStateException("The channel was created, but its permissions"
+ " could not be set: " + RequestException.rootMessage(e));
}
return channelId;
});
}
/** Applies an edited channel: its changed properties first, then its needed-power permissions. */
public CompletableFuture<Void> edit(int channelId, Map<String, String> changes,
Map<String, Integer> setPermissions, Collection<String> removePermissions) {
return uplink.requestVoid(() -> {
editProperties(channelId, changes);
writePermissions(channelId, setPermissions, removePermissions);
if (changes.containsKey("channel_description")) refreshDescription(channelId);
});
}
/** Deletes a channel, with its sub-channels and whoever is in them moved out when {@code force}. */
public CompletableFuture<Void> delete(int channelId, boolean force) {
return uplink.requestVoid(() -> uplink.socket().executeCommand(new SingleCommand("channeldelete",
ProtocolRole.CLIENT,
new CommandSingleParameter("cid", Integer.toString(channelId)),
new CommandSingleParameter("force", force ? "1" : "0"))).complete());
}
private int createNow(int parentId, Map<String, String> properties) throws Exception {
SingleCommand cmd = new SingleCommand("channelcreate", ProtocolRole.CLIENT); SingleCommand cmd = new SingleCommand("channelcreate", ProtocolRole.CLIENT);
cmd.add(new CommandSingleParameter("cpid", Integer.toString(parentId))); cmd.add(new CommandSingleParameter("cpid", Integer.toString(parentId)));
for (Map.Entry<String, String> property : properties.entrySet()) { for (Map.Entry<String, String> property : properties.entrySet()) {
cmd.add(new CommandSingleParameter(property.getKey(), property.getValue())); cmd.add(new CommandSingleParameter(property.getKey(), property.getValue()));
} }
for (SingleCommand answer : conn.socket().executeCommand(cmd).get()) { for (SingleCommand answer : uplink.socket().executeCommand(cmd).get()) {
int cid = parseInt(answer.toMap().get("cid"), -1); int cid = parseInt(answer.toMap().get("cid"), -1);
if (cid > 0) return cid; if (cid > 0) return cid;
} }
// Some servers acknowledge the command without naming the channel; the // Some servers acknowledge the command without naming the channel; the
// notifychannelcreated they also send does name it, so read it off the model // notifychannelcreated they also send does name it, so read it off the model
// once that event has been handled. // once that event has been handled.
conn.awaitEventsProcessed(); uplink.awaitEventsProcessed();
ChannelNode created = conn.getModel().findChannelByName(parentId, properties.get("channel_name")); ChannelNode created = model.findChannelByName(parentId, properties.get("channel_name"));
if (created == null) throw new IllegalStateException("The server did not report the new channel"); if (created == null) throw new IllegalStateException("The server did not report the new channel");
return created.id; return created.id;
} }
/** Applies {@code changes} (property name to value) with a single {@code channeledit}. */ /** Applies {@code changes} (property name to value) with a single {@code channeledit}. */
void edit(int channelId, Map<String, String> changes) throws Exception { private void editProperties(int channelId, Map<String, String> changes) throws Exception {
if (changes.isEmpty()) return; if (changes.isEmpty()) return;
SingleCommand cmd = new SingleCommand("channeledit", ProtocolRole.CLIENT); SingleCommand cmd = new SingleCommand("channeledit", ProtocolRole.CLIENT);
cmd.add(new CommandSingleParameter("cid", Integer.toString(channelId))); cmd.add(new CommandSingleParameter("cid", Integer.toString(channelId)));
for (Map.Entry<String, String> change : changes.entrySet()) { for (Map.Entry<String, String> change : changes.entrySet()) {
cmd.add(new CommandSingleParameter(change.getKey(), change.getValue())); cmd.add(new CommandSingleParameter(change.getKey(), change.getValue()));
} }
conn.socket().executeCommand(cmd).complete(); uplink.socket().executeCommand(cmd).complete();
} }
/** Deletes a channel, with its sub-channels and whoever is in them moved out when {@code force}. */ /**
void delete(int channelId, boolean force) throws Exception { * The server does not tell the invoker about their own description change, so a
conn.socket().executeCommand(new SingleCommand("channeldelete", ProtocolRole.CLIENT, * description already shown is read again. Refused, the old one stays.
new CommandSingleParameter("cid", Integer.toString(channelId)), */
new CommandSingleParameter("force", force ? "1" : "0"))).complete(); private void refreshDescription(int channelId) {
ChannelNode node = model.getChannel(channelId);
if (node == null || !node.descriptionLoaded) return;
node.descriptionLoaded = false;
try {
uplink.socket().executeCommand(new SingleCommand("channelgetdescription", ProtocolRole.CLIENT,
new CommandSingleParameter("cid", Integer.toString(channelId)))).complete();
} catch (Exception ignored) {
}
} }
// ---- channel permissions ---- // ---- channel permissions ----
/** /**
* Reads the permissions set directly on a channel. * Reads the permissions set directly on a channel. Fails when the server does not let
* us look at them.
* *
* @return permission name to value, holding only the permissions the channel itself * @return permission name to value, holding only the permissions the channel itself
* carries — anything inherited from a group is absent * carries — anything inherited from a group is absent
*/ */
Map<String, Integer> readPermissions(int channelId) throws Exception { public CompletableFuture<Map<String, Integer>> permissions(int channelId) {
if (!conn.getModel().hasPermissionNames()) { return uplink.request(() -> readPermissions(channelId));
}
private Map<String, Integer> readPermissions(int channelId) throws Exception {
if (!model.permissions().hasNames()) {
// channelpermlist reports numeric ids, which only the permissionlist response // channelpermlist reports numeric ids, which only the permissionlist response
// gives names to; without it the values could not be told apart. // gives names to; without it the values could not be told apart.
throw new IllegalStateException("The server did not send its permission list"); throw new IllegalStateException("The server did not send its permission list");
@@ -123,17 +245,17 @@ final class ChannelAdmin {
try { try {
SingleCommand cmd = new SingleCommand("channelpermlist", ProtocolRole.CLIENT, SingleCommand cmd = new SingleCommand("channelpermlist", ProtocolRole.CLIENT,
new CommandSingleParameter("cid", Integer.toString(channelId))); new CommandSingleParameter("cid", Integer.toString(channelId)));
conn.socket().executeCommand(cmd).complete(); uplink.socket().executeCommand(cmd).complete();
// The entries were queued on the event thread before the command's own reply // The entries were queued on the event thread before the command's own reply
// was read, so draining that thread is what guarantees they have all landed. // was read, so draining that thread is what guarantees they have all landed.
conn.awaitEventsProcessed(); uplink.awaitEventsProcessed();
} finally { } finally {
permRequest = null; permRequest = null;
} }
Map<String, Integer> byName = new LinkedHashMap<>(); Map<String, Integer> byName = new LinkedHashMap<>();
for (Map.Entry<Integer, Integer> entry : request.values.entrySet()) { for (Map.Entry<Integer, Integer> entry : request.values.entrySet()) {
String name = conn.getModel().permissionName(entry.getKey()); String name = model.permissions().name(entry.getKey());
if (name != null) byName.put(name, entry.getValue()); if (name != null) byName.put(name, entry.getValue());
} }
return byName; return byName;
@@ -153,7 +275,7 @@ final class ChannelAdmin {
* Sets and clears channel permissions by name. A permission set to a value is added or * Sets and clears channel permissions by name. A permission set to a value is added or
* updated; one that is cleared is removed so the channel inherits it again. * updated; one that is cleared is removed so the channel inherits it again.
*/ */
void writePermissions(int channelId, Map<String, Integer> set, Collection<String> remove) private void writePermissions(int channelId, Map<String, Integer> set, Collection<String> remove)
throws Exception { throws Exception {
if (!set.isEmpty()) { if (!set.isEmpty()) {
List<SingleCommand> parts = new ArrayList<>(set.size()); List<SingleCommand> parts = new ArrayList<>(set.size());
@@ -177,7 +299,7 @@ final class ChannelAdmin {
private void send(String name, int channelId, List<SingleCommand> parts) throws Exception { private void send(String name, int channelId, List<SingleCommand> parts) throws Exception {
MultiCommand cmd = new MultiCommand(name, ProtocolRole.CLIENT, parts); MultiCommand cmd = new MultiCommand(name, ProtocolRole.CLIENT, parts);
cmd.add(new CommandSingleParameter("cid", Integer.toString(channelId))); cmd.add(new CommandSingleParameter("cid", Integer.toString(channelId)));
conn.socket().executeCommand(cmd).complete(); uplink.socket().executeCommand(cmd).complete();
} }
// ---- the server's icon store ---- // ---- the server's icon store ----
@@ -186,10 +308,14 @@ final class ChannelAdmin {
* The ids of the icons uploaded to this virtual server, which live in channel 0's file * The ids of the icons uploaded to this virtual server, which live in channel 0's file
* repository as {@code /icon_<id>}. * repository as {@code /icon_<id>}.
*/ */
List<Long> listIcons() throws Exception { public CompletableFuture<List<Long>> icons() {
return uplink.request(this::listIcons);
}
private List<Long> listIcons() throws Exception {
List<Long> ids = new ArrayList<>(); List<Long> ids = new ArrayList<>();
boolean hasIconDirectory = false; boolean hasIconDirectory = false;
for (RemoteFile file : fileTransfers().list(0, "", "/")) { for (RemoteFile file : uplink.files().list(0, "", "/")) {
if (file.isDirectory()) { if (file.isDirectory()) {
hasIconDirectory |= file.getName().equals(ICON_DIRECTORY); hasIconDirectory |= file.getName().equals(ICON_DIRECTORY);
continue; continue;
@@ -199,7 +325,7 @@ final class ChannelAdmin {
// Newer servers keep the icons in their own directory rather than loose in the // Newer servers keep the icons in their own directory rather than loose in the
// repository's root; both layouts exist, so whichever this server uses is read. // repository's root; both layouts exist, so whichever this server uses is read.
if (hasIconDirectory) { if (hasIconDirectory) {
for (RemoteFile file : fileTransfers().list(0, "", "/" + ICON_DIRECTORY)) { for (RemoteFile file : uplink.files().list(0, "", "/" + ICON_DIRECTORY)) {
if (!file.isDirectory()) addIcon(ids, file); if (!file.isDirectory()) addIcon(ids, file);
} }
} }
@@ -217,7 +343,11 @@ final class ChannelAdmin {
* *
* @return the icon's id, which TeamSpeak derives from the file's CRC32 * @return the icon's id, which TeamSpeak derives from the file's CRC32
*/ */
long uploadIcon(File source) throws Exception { public CompletableFuture<Long> uploadIcon(File source) {
return uplink.request(() -> upload(source));
}
private long upload(File source) throws Exception {
byte[] data = Files.readAllBytes(source.toPath()); byte[] data = Files.readAllBytes(source.toPath());
if (data.length == 0) throw new IllegalArgumentException("That file is empty"); if (data.length == 0) throw new IllegalArgumentException("That file is empty");
if (data.length > TeamspeakConnection.MAX_ICON_BYTES) { if (data.length > TeamspeakConnection.MAX_ICON_BYTES) {
@@ -229,7 +359,7 @@ final class ChannelAdmin {
long id = crc.getValue(); long id = crc.getValue();
CountDownLatch done = new CountDownLatch(1); CountDownLatch done = new CountDownLatch(1);
FileTransfer transfer = fileTransfers().upload(0, "", "/icon_" + id, source, true, t -> { FileTransfer transfer = uplink.files().upload(0, "", "/icon_" + id, source, true, t -> {
if (t.isDone()) done.countDown(); if (t.isDone()) done.countDown();
}); });
if (!done.await(ICON_UPLOAD_TIMEOUT_MS, TimeUnit.MILLISECONDS)) { if (!done.await(ICON_UPLOAD_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
@@ -242,14 +372,8 @@ final class ChannelAdmin {
return id; return id;
} }
void deleteIcon(long iconId) throws Exception { public CompletableFuture<Void> deleteIcon(long iconId) {
fileTransfers().delete(0, "", "/icon_" + iconId); return uplink.requestVoid(() -> uplink.files().delete(0, "", "/icon_" + iconId));
}
private FileTransferManager fileTransfers() {
FileTransferManager ft = conn.fileTransfers();
if (ft == null) throw new IllegalStateException("Not connected");
return ft;
} }
// ---- helpers ---- // ---- helpers ----
@@ -0,0 +1,78 @@
package eu.lixko.ts3j.client.net;
import eu.lixko.ts3j.client.net.filetransfer.FileTransfer;
import eu.lixko.ts3j.client.net.filetransfer.RemoteFile;
import eu.lixko.ts3j.client.sound.SoundEvent;
import java.io.File;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* The channels' file repositories: browsing, managing and transferring files. The listing
* and management calls block; call them off the UI thread. They throw when not connected
* or when the server refuses.
*/
public final class ChannelFiles {
private final Uplink uplink;
private final Announcer announce;
ChannelFiles(Uplink uplink, Announcer announce) {
this.uplink = uplink;
this.announce = announce;
}
/** Whether a live connection capable of file transfers is available. */
public boolean isAvailable() {
return uplink.canTransferFiles();
}
/** Lists the files under {@code path} in a channel's repository. */
public List<RemoteFile> list(int channelId, String channelPassword, String path) throws Exception {
return uplink.files().list(channelId, channelPassword, path);
}
public void createDirectory(int channelId, String channelPassword, String dirPath) throws Exception {
uplink.files().createDirectory(channelId, channelPassword, dirPath);
}
public void delete(int channelId, String channelPassword, String fullPath) throws Exception {
uplink.files().delete(channelId, channelPassword, fullPath);
}
public void rename(int channelId, String channelPassword, String oldFullPath, String newFullPath)
throws Exception {
uplink.files().rename(channelId, channelPassword, oldFullPath, newFullPath);
}
/** Begins downloading a channel file to {@code target}; progress arrives via {@code listener}. */
public FileTransfer download(int channelId, String channelPassword, String remoteFullPath,
File target, FileTransfer.Listener listener) {
return uplink.files().download(channelId, channelPassword, remoteFullPath, target, announcing(listener));
}
/** Begins uploading {@code source} into a channel; progress arrives via {@code listener}. */
public FileTransfer upload(int channelId, String channelPassword, String remoteFullPath,
File source, boolean overwrite, FileTransfer.Listener listener) {
return uplink.files().upload(channelId, channelPassword, remoteFullPath, source, overwrite, announcing(listener));
}
/**
* Wraps a transfer listener so the completion and failure sounds play once the
* transfer finishes, whoever is watching it.
*/
private FileTransfer.Listener announcing(FileTransfer.Listener listener) {
AtomicBoolean announced = new AtomicBoolean();
return transfer -> {
FileTransfer.State state = transfer.getState();
if (state != FileTransfer.State.CANCELLED && transfer.isDone()
&& announced.compareAndSet(false, true)) {
announce.sound(state == FileTransfer.State.COMPLETED
? SoundEvent.OTHER_FILETRANSFER_COMPLETE
: SoundEvent.OTHER_FILETRANSFER_FAILED, announce.serverVars());
}
if (listener != null) listener.onTransferChanged(transfer);
};
}
}
@@ -19,6 +19,8 @@ public final class ChannelNode {
public volatile boolean hasPassword; public volatile boolean hasPassword;
public volatile boolean permanent; public volatile boolean permanent;
public volatile int maxClients = -1; public volatile int maxClients = -1;
/** The talk power a client needs to talk here ({@code channel_needed_talk_power}). */
public volatile int neededTalkPower;
/** Id of the channel's custom icon in the server's file repository, or 0 for none. */ /** Id of the channel's custom icon in the server's file repository, or 0 for none. */
public volatile long iconId; public volatile long iconId;
/** Whether the server sends us this channel's client list; set from the subscription events. */ /** Whether the server sends us this channel's client list; set from the subscription events. */
@@ -0,0 +1,114 @@
package eu.lixko.ts3j.client.net;
import eu.lixko.ts3j.client.chat.ChatScope;
import eu.lixko.ts3j.client.chatlog.ChatLogStore;
import eu.lixko.ts3j.client.config.Settings;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;
/**
* A connection's chat log on disk: opened once the server is known, it hands the frontend
* the history and keeps what is said, and the server tab's log lines, from then on. Without
* one (turned off, or unavailable) everything still reaches the frontend, only unkept.
*/
final class ChatLog {
private final Settings settings;
private final ConnectionListener ui;
private volatile ChatLogStore store;
ChatLog(Settings settings, ConnectionListener ui) {
this.settings = settings;
this.ui = ui;
}
/**
* Opens the log for the server with {@code serverUniqueId} and hands the frontend its
* server and channel history.
*/
void open(String serverUniqueId) {
store = null;
if (!settings.chatLogs.get()) return;
try {
if (serverUniqueId == null) {
ui.onStatus("Chat logs unavailable: the server's unique id is not known");
return;
}
String dir = settings.chatLogDir.get() == null ? "" : settings.chatLogDir.get().trim();
// Android < API 34 lacks Path.of; original:
// ChatLogStore logs = new ChatLogStore(dir.isEmpty() ? ChatLogStore.defaultRoot() : Path.of(dir), uniqueId);
ChatLogStore logs = new ChatLogStore(dir.isEmpty() ? ChatLogStore.defaultRoot() : Paths.get(dir), serverUniqueId);
store = logs;
logs.begin();
List<String> serverHistory = logs.serverHtmlHistory();
List<String> channelHistory = logs.channelHtmlHistory();
ui.onChatHistory(ChatScope.SERVER, serverHistory);
ui.onChatHistory(ChatScope.CHANNEL, channelHistory);
ui.onStatus("Loaded chat logs from " + logs.serverDir()
+ " (" + serverHistory.size() + " server, " + channelHistory.size() + " channel)");
} catch (Exception e) {
store = null;
ui.onStatus("Chat logs unavailable: " + RequestException.rootMessage(e));
}
}
void close() {
store = null;
}
/** Hands the frontend what was said with the client with {@code uniqueId} before. */
void loadPrivateHistory(int clientId, String name, String uniqueId) {
ChatLogStore logs = store;
if (logs == null || uniqueId == null || uniqueId.isBlank()) return;
try {
ui.onPrivateChatHistory(clientId, name, logs.privateHtmlHistory(uniqueId));
} catch (IOException e) {
ui.onStatus("Private chat log unavailable: " + RequestException.rootMessage(e));
}
}
void received(ChatScope scope, int fromClientId, String fromUniqueId, String fromName,
String message) {
ChatLogStore logs = store;
if (logs == null) return;
try {
logs.appendMessage(scope, false, fromClientId, fromUniqueId, fromName, message);
} catch (IOException e) {
ui.onStatus("Could not write chat log: " + RequestException.rootMessage(e));
}
}
/** What we said; a private message is kept with {@code peerUniqueId}'s log, and dropped without one. */
void sent(ChatScope scope, int selfClientId, String selfUniqueId, String selfName,
String peerUniqueId, String message) {
ChatLogStore logs = store;
if (logs == null) return;
try {
if (scope == ChatScope.PRIVATE) {
if (peerUniqueId == null || peerUniqueId.isBlank()) return;
logs.appendPrivateMessage(peerUniqueId, true, selfClientId, selfUniqueId, selfName, message);
} else {
logs.appendMessage(scope, true, selfClientId, selfUniqueId, selfName, message);
}
} catch (IOException e) {
ui.onStatus("Could not write chat log: " + RequestException.rootMessage(e));
}
}
/** Shows a line in the server tab's log, the way native TS3 reports server activity, and keeps it. */
void serverEvent(String message) {
ChatLogStore logs = store;
if (logs == null) {
ui.onServerLog(message);
return;
}
try {
ui.onServerLogHtml(logs.appendServerEvent(message));
} catch (IOException e) {
ui.onServerLog(message);
ui.onStatus("Could not write server log: " + RequestException.rootMessage(e));
}
}
}
@@ -0,0 +1,225 @@
package eu.lixko.ts3j.client.net;
import com.github.manevolent.ts3j.api.Client;
import com.github.manevolent.ts3j.command.MultiCommand;
import com.github.manevolent.ts3j.command.SingleCommand;
import com.github.manevolent.ts3j.command.parameter.CommandSingleParameter;
import com.github.manevolent.ts3j.protocol.ProtocolRole;
import com.github.manevolent.ts3j.protocol.socket.client.LocalTeamspeakClientSocket;
import eu.lixko.ts3j.client.sound.SoundEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.IntSupplier;
/**
* What we do to other clients (or ourselves among them): moving, kicking, banning, groups,
* talk power, pokes, and reading or editing their details.
*
* <p>The actions run in the background and report a failure in the log; the requests that
* return a future fail it with a {@link RequestException} instead.
*/
public final class ClientAdmin {
/** The longest reason the protocol carries with a kick. */
public static final int KICK_REASON_LIMIT = 40;
/** The protocol's reason ids for the two flavours of <b>clientkick</b>. */
private static final int REASON_KICK_CHANNEL = 4;
private static final int REASON_KICK_SERVER = 5;
private final Uplink uplink;
private final ServerModel model;
private final Announcer announce;
private final IntSupplier selfClientId;
/** Tells the frontend a client's details changed where the server will not. */
private final Runnable infoUpdated;
ClientAdmin(Uplink uplink, ServerModel model, Announcer announce, IntSupplier selfClientId, Runnable infoUpdated) {
this.uplink = uplink;
this.model = model;
this.announce = announce;
this.selfClientId = selfClientId;
this.infoUpdated = infoUpdated;
}
/**
* Moves several clients (ourselves among them, if wanted) into a channel in one piped
* command. Clients already in it are left out, which the server would refuse.
*/
public void move(Collection<Integer> clientIds, int channelId) {
List<SingleCommand> rows = new ArrayList<>(clientIds.size());
for (int id : clientIds) {
ClientEntry client = model.getClient(id);
if (client != null && client.channelId == channelId) continue;
rows.add(new SingleCommand("clientmove", ProtocolRole.CLIENT,
new CommandSingleParameter("clid", Integer.toString(id))));
}
if (rows.isEmpty()) return;
act(rows.size() == 1 ? "Could not move client: " : "Could not move clients: ", sock -> {
MultiCommand cmd = new MultiCommand("clientmove", ProtocolRole.CLIENT, rows);
cmd.add(new CommandSingleParameter("cid", Integer.toString(channelId)));
sock.executeCommand(cmd).complete();
});
}
/**
* Kicks clients out of their channels in one command; we are never among them, nor are
* clients already in the default channel, as the server would refuse the whole command.
*/
public void kickFromChannel(Collection<Integer> clientIds, String reason) {
int defaultChannel = model.defaultChannelId();
List<Integer> ids = new ArrayList<>(clientIds.size());
for (int id : clientIds) {
ClientEntry client = model.getClient(id);
if (client == null || client.channelId != defaultChannel) ids.add(id);
}
kick(ids, REASON_KICK_CHANNEL, reason, "channel");
}
/** Kicks clients off the server in one command; we are never among them. */
public void kickFromServer(Collection<Integer> clientIds, String reason) {
kick(clientIds, REASON_KICK_SERVER, reason, "server");
}
private void kick(Collection<Integer> clientIds, int reasonId, String reason, String from) {
int self = selfClientId.getAsInt();
List<SingleCommand> rows = new ArrayList<>(clientIds.size());
for (int id : clientIds) {
if (id == self) continue;
rows.add(new SingleCommand("clientkick", ProtocolRole.CLIENT,
new CommandSingleParameter("clid", Integer.toString(id))));
}
if (rows.isEmpty()) return;
String errorPrefix = "Could not kick " + (rows.size() == 1 ? "client" : "clients") + " from the " + from + ": ";
act(errorPrefix, sock -> {
MultiCommand cmd = new MultiCommand("clientkick", ProtocolRole.CLIENT, rows);
cmd.add(new CommandSingleParameter("reasonid", Integer.toString(reasonId)));
if (reason != null && !reason.isEmpty()) {
cmd.add(new CommandSingleParameter("reasonmsg", reason));
}
sock.executeCommand(cmd).complete();
});
}
/**
* Bans a client from the server.
*
* @param seconds how long the ban lasts, or 0 for a permanent one
*/
public void ban(int clientId, long seconds, String reason) {
act("Could not ban client: ", sock -> sock.banClient(clientId,
seconds <= 0 ? null : (int) Math.min(seconds, Integer.MAX_VALUE),
reason == null || reason.isEmpty() ? null : reason));
}
/** Assigns or removes a server group for a client (by database id, as {@code servergroupaddclient} needs). */
public void setServerGroup(int clientDatabaseId, int groupId, boolean assign) {
act("Could not " + (assign ? "assign" : "remove") + " server group: ", sock -> {
if (assign) sock.serverGroupAddClient(groupId, clientDatabaseId);
else sock.serverGroupRemoveClient(groupId, clientDatabaseId);
});
}
/** Assigns a channel group for a client in the channel it currently sits in. */
public void setChannelGroup(int clientDatabaseId, int channelId, int groupId) {
act("Could not set channel group: ", sock -> {
SingleCommand cmd = new SingleCommand("setclientchannelgroup", ProtocolRole.CLIENT);
cmd.add(new CommandSingleParameter("cgid", Integer.toString(groupId)));
cmd.add(new CommandSingleParameter("cid", Integer.toString(channelId)));
cmd.add(new CommandSingleParameter("cldbid", Integer.toString(clientDatabaseId)));
sock.executeCommand(cmd).complete();
});
}
public void poke(int clientId, String message) {
act("Poke failed: ", sock -> {
sock.clientPoke(clientId, message);
announce.sound(SoundEvent.OTHER_SENT_POKE, announce.clientVars(clientId, null));
});
}
/** Grants or revokes clients' talk power, which lets them talk whatever their channel needs. */
public void setTalker(Collection<Integer> clientIds, boolean talker) {
if (clientIds.isEmpty()) return;
act(talker ? "Error granting talk power: " : "Error revoking talk power: ", sock -> {
for (int id : clientIds) setTalker(sock, id, talker);
});
}
/**
* Grants talk power to whoever in a channel has waited longest for it, first revoking
* it from everyone who has it there when {@code revokeOthers}.
*/
public void grantNextTalkPower(int channelId, boolean revokeOthers) {
ClientEntry next = model.nextTalkRequest(channelId);
List<ClientEntry> talkers = revokeOthers ? model.talkersIn(channelId) : List.of();
if (next == null && talkers.isEmpty()) return;
act("Error granting talk power: ", sock -> {
for (ClientEntry c : talkers) {
if (c != next) setTalker(sock, c.id, false);
}
if (next != null) setTalker(sock, next.id, true);
});
}
private static void setTalker(LocalTeamspeakClientSocket sock, int clientId, boolean talker) throws Exception {
sock.executeCommand(new SingleCommand("clientedit", ProtocolRole.CLIENT,
new CommandSingleParameter("clid", Integer.toString(clientId)),
new CommandSingleParameter("client_is_talker", talker ? "1" : "0"))).complete();
}
/**
* Asks for a client's version and platform, the only details the enter-view event
* lacks. The answer arrives as a client update, see {@link ConnectionEventHandler#onClientChanged}.
* Uses {@code clientgetvariables}, not {@code clientinfo}, which counts heavily against the
* server's flood protection. May be refused; the details then stay as they are.
*/
public void requestInfo(int clientId) {
uplink.submit(sock -> sock.executeCommand(new SingleCommand("clientgetvariables", ProtocolRole.CLIENT,
new CommandSingleParameter("clid", Integer.toString(clientId)))).complete(), e -> {
});
}
/**
* Reads a client's description straight from the server, so an editor opens on the
* live text instead of whatever an earlier info request cached.
*/
public CompletableFuture<String> description(int clientId) {
return uplink.request(() -> {
Client c = uplink.socket().getClientInfo(clientId);
String description = c == null ? "" : TeamspeakConnection.orEmpty(c.get("client_description"));
ClientEntry e = model.getClient(clientId);
if (e != null) e.description = description;
return description;
});
}
/**
* Changes a client's description. Unlike the nickname or the away state, this is not
* a {@code clientupdate} property even for ourselves: the server only takes it
* through {@code clientedit}, gated by {@code b_client_modify_own_description}.
*/
public CompletableFuture<Void> setDescription(int clientId, String description) {
boolean self = clientId == selfClientId.getAsInt();
return uplink.requestVoid(() -> {
SingleCommand cmd = new SingleCommand("clientedit", ProtocolRole.CLIENT);
cmd.add(new CommandSingleParameter("clid", Integer.toString(clientId)));
cmd.add(new CommandSingleParameter("client_description", description));
uplink.socket().executeCommand(cmd).complete();
// Only the other clients are told about our own update, so the local entry
// (and the info panel showing it) has to be caught up here.
if (self) {
ClientEntry e = model.getClient(clientId);
if (e != null) e.description = description;
infoUpdated.run();
}
});
}
private void act(String errorPrefix, Uplink.Action action) {
uplink.submit(action, e -> announce.error(errorPrefix, e));
}
}
@@ -0,0 +1,112 @@
package eu.lixko.ts3j.client.net;
import eu.lixko.ts3j.client.audio.VoiceOutput;
import eu.lixko.ts3j.client.config.Settings;
import eu.lixko.ts3j.client.contacts.Contact;
import eu.lixko.ts3j.client.contacts.ContactStore;
import java.util.function.Supplier;
/**
* The contact list as it applies to the clients on this server: the names they are shown
* under, their automatic mute and volume, whose whispers we hear, and where they were seen.
*/
public final class ClientContacts {
private final ContactStore store;
private final Settings settings;
private final ServerModel model;
private final OwnClient own;
private final Uplink uplink;
/** The server address we are on, recorded with a sighting. */
private final Supplier<String> address;
ClientContacts(ContactStore store, Settings settings, ServerModel model, OwnClient own, Uplink uplink,
Supplier<String> address) {
this.store = store;
this.settings = settings;
this.model = model;
this.own = own;
this.uplink = uplink;
this.address = address;
}
/** Friends, blocked clients and their per-client filters, shared by every server. */
public ContactStore store() {
return store;
}
/** The name a client is shown under: its contact's custom name where it has one. */
public String displayName(ClientEntry client) {
return store.displayName(client.uniqueId, client.nickname);
}
/**
* Whether a whisper from a client is played, per the global whisper policy and the
* client's contact entry. A client that has already left is judged by the policy alone.
*/
boolean isWhisperAllowed(int clientId) {
Settings.WhisperPolicy policy = settings.whisperPolicy.get();
if (policy == Settings.WhisperPolicy.NOBODY) return false;
ClientEntry c = model.getClient(clientId);
Contact contact = c == null ? null : store.find(c.uniqueId);
if (contact != null) return contact.whisperAllowed;
return policy == Settings.WhisperPolicy.ALLOW_UNLESS_DENIED;
}
/**
* Applies a client's contact entry to its playback — the automatic mute and the
* volume modifier — and records the sighting. Called when the client appears, which
* is also when its myTeamSpeak ID can first match a contact.
*/
void apply(ClientEntry client) {
store.link(client.uniqueId, client.myTeamSpeakId);
Contact contact = applyPlayback(client);
if (contact != null) store.markSeen(client.uniqueId, model.getServerName(), address.get());
}
private Contact applyPlayback(ClientEntry client) {
if (client == null || client.self) return null;
Contact contact = store.find(client.uniqueId);
VoiceOutput out = own.playback();
if (contact != null && out != null) {
if (contact.automute) out.setClientMuted(client.id, true);
out.setClientVolume(client.id, contact.volumeGain());
}
return contact;
}
/**
* Re-applies every contact entry to the clients on the server, after the list changed.
* A client that just became a contact is also marked as seen. One seen before keeps
* where it was seen: with it on two servers, each re-application would claim it for its
* own server, which is a change that triggers the other's re-application, and so on.
*/
public void applyAll() {
if (!uplink.isUp()) return;
for (ClientEntry c : model.allClients()) {
Contact contact = applyPlayback(c);
if (contact != null && contact.lastSeen == null) {
store.markSeen(c.uniqueId, model.getServerName(), address.get());
}
}
}
/** Remembers a per-client volume, in the contact entry when the client has one. */
public void setVolumeModifier(ClientEntry client, double decibels) {
VoiceOutput out = own.playback();
if (out != null) out.setClientVolume(client.id, Math.pow(10.0, decibels / 20.0));
Contact contact = store.find(client.uniqueId);
if (contact == null) return;
contact.hasVolumeModifier = decibels != 0;
contact.volumeModifier = decibels;
store.put(contact);
}
public double volumeModifier(ClientEntry client) {
VoiceOutput out = own.playback();
if (out == null) return 0;
double gain = out.getClientVolume(client.id);
return gain <= 0 ? -60 : 20.0 * Math.log10(gain);
}
}
@@ -11,11 +11,19 @@ public final class ClientEntry {
/** How text-to-speech should say the nickname ({@code client_nickname_phonetic}). */ /** How text-to-speech should say the nickname ({@code client_nickname_phonetic}). */
public volatile String phoneticNickname = ""; public volatile String phoneticNickname = "";
public volatile String uniqueId = ""; public volatile String uniqueId = "";
/** {@code client_myteamspeak_id}: the client's myTeamSpeak account, empty when it shares none. */
public volatile String myTeamSpeakId = "";
public volatile int databaseId; public volatile int databaseId;
public volatile int type; // 0 = normal voice client, 1 = server-query public volatile int type; // 0 = normal voice client, 1 = server-query
public volatile int talkPower; public volatile int talkPower;
/** Waiting for a moderator to grant talk power ({@code client_talk_request}). */ /** Waiting for a moderator to grant talk power ({@code client_talk_request}). */
public volatile boolean talkRequest; public volatile boolean talkRequest;
/** When the request was made, in epoch seconds; 0 when unknown or there is none. */
public volatile long talkRequestTime;
/** The reason given with the request ({@code client_talk_request_msg}). */
public volatile String talkRequestMessage = "";
/** Granted talk power: may talk whatever the channel needs ({@code client_is_talker}). */
public volatile boolean talker;
public volatile int[] serverGroupIds = new int[0]; public volatile int[] serverGroupIds = new int[0];
public volatile int channelGroupId; public volatile int channelGroupId;
@@ -7,45 +7,53 @@ import com.github.manevolent.ts3j.event.UnknownTeamspeakEvent;
import com.github.manevolent.ts3j.protocol.ProtocolRole; import com.github.manevolent.ts3j.protocol.ProtocolRole;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.concurrent.CompletableFuture;
/** /**
* The server's complaints: filing, listing and removing them. * The server's complaints: filing, listing and removing them.
* *
* <p>Split out of {@link TeamspeakConnection} like {@link BanAdmin}, and answered the same * <p>Answered like {@link BanAdmin}: {@code complainlist} replies with
* way: {@code complainlist} replies with {@code notifycomplainlist} events ahead of the * {@code notifycomplainlist} events ahead of the command's own completion. Requests run in
* command's own completion. Every call here blocks and must run off the UI thread; the * the background and fail with a {@link RequestException}.
* connection's public wrappers do that.
*/ */
final class ComplaintAdmin { public final class ComplaintAdmin {
/** The longest reason a complaint may carry. */
public static final int REASON_LIMIT = 200;
/** What {@code complainlist} answers when there are no complaints at all. */ /** What {@code complainlist} answers when there are no complaints at all. */
private static final int ERROR_DATABASE_EMPTY_RESULT = 0x0501; private static final int ERROR_DATABASE_EMPTY_RESULT = 0x0501;
/** What {@code complainadd} answers when we already complained about that client. */ /** What {@code complainadd} answers when we already complained about that client. */
private static final int ERROR_DATABASE_DUPLICATE_ENTRY = 0x0502; private static final int ERROR_DATABASE_DUPLICATE_ENTRY = 0x0502;
private final TeamspeakConnection conn; private final Uplink uplink;
private final Announcer announce;
/** The {@code complainlist} reply in progress; one request may be in flight at a time. */ /** The {@code complainlist} reply in progress; one request may be in flight at a time. */
private volatile List<Complaint> listing; private volatile List<Complaint> listing;
ComplaintAdmin(TeamspeakConnection conn) { ComplaintAdmin(Uplink uplink, Announcer announce) {
this.conn = conn; this.uplink = uplink;
this.announce = announce;
} }
List<Complaint> list() throws Exception { public CompletableFuture<List<Complaint>> list() {
return uplink.request(() -> {
List<Complaint> complaints = Collections.synchronizedList(new ArrayList<>()); List<Complaint> complaints = Collections.synchronizedList(new ArrayList<>());
listing = complaints; listing = complaints;
try { try {
conn.socket().executeCommand(new SingleCommand("complainlist", ProtocolRole.CLIENT)).complete(); uplink.socket().executeCommand(new SingleCommand("complainlist", ProtocolRole.CLIENT)).complete();
conn.awaitEventsProcessed(); uplink.awaitEventsProcessed();
} catch (CommandException e) { } catch (CommandException e) {
if (e.getErrorId() != ERROR_DATABASE_EMPTY_RESULT) throw e; if (e.getErrorId() != ERROR_DATABASE_EMPTY_RESULT) throw e;
} finally { } finally {
listing = null; listing = null;
} }
return new ArrayList<>(complaints); return new ArrayList<>(complaints);
});
} }
void onListEntry(UnknownTeamspeakEvent e) { void onListEntry(UnknownTeamspeakEvent e) {
@@ -53,27 +61,39 @@ final class ComplaintAdmin {
if (complaints != null) complaints.add(Complaint.from(e.getMap())); if (complaints != null) complaints.add(Complaint.from(e.getMap()));
} }
/** Files a complaint about a client; the server takes one per client from each of us. */ /**
void add(int targetDbId, String message) throws Exception { * Complains about an online client to the server's admins; the server takes one per
* client from each of us. The outcome goes to the server tab's log.
*/
public void complain(ClientEntry client, String reason) {
uplink.submit(sock -> {
try { try {
conn.socket().executeCommand(new SingleCommand("complainadd", ProtocolRole.CLIENT, sock.executeCommand(new SingleCommand("complainadd", ProtocolRole.CLIENT,
new CommandSingleParameter("tcldbid", Integer.toString(targetDbId)), new CommandSingleParameter("tcldbid", Integer.toString(client.databaseId)),
new CommandSingleParameter("message", message))).complete(); new CommandSingleParameter("message", reason))).complete();
} catch (CommandException e) { } catch (CommandException e) {
if (e.getErrorId() != ERROR_DATABASE_DUPLICATE_ENTRY) throw e; if (e.getErrorId() != ERROR_DATABASE_DUPLICATE_ENTRY) throw e;
throw new IllegalStateException("Cannot add multiple complaints about the same client."); throw new IllegalStateException("Cannot add multiple complaints about the same client.");
} }
announce.log("Complaint sent.");
}, e -> announce.error("Failed to send complaint: ", e));
} }
void delete(Complaint complaint) throws Exception { /**
conn.socket().executeCommand(new SingleCommand("complaindel", ProtocolRole.CLIENT, * Removes every complaint about each of {@code targetDbIds}, then each of {@code single},
* stopping at the first the server refuses.
*/
public CompletableFuture<Void> delete(Collection<Integer> targetDbIds, Collection<Complaint> single) {
return uplink.requestVoid(() -> {
for (int target : targetDbIds) {
uplink.socket().executeCommand(new SingleCommand("complaindelall", ProtocolRole.CLIENT,
new CommandSingleParameter("tcldbid", Integer.toString(target)))).complete();
}
for (Complaint complaint : single) {
uplink.socket().executeCommand(new SingleCommand("complaindel", ProtocolRole.CLIENT,
new CommandSingleParameter("tcldbid", Integer.toString(complaint.targetDbId())), new CommandSingleParameter("tcldbid", Integer.toString(complaint.targetDbId())),
new CommandSingleParameter("fcldbid", Integer.toString(complaint.fromDbId())))).complete(); new CommandSingleParameter("fcldbid", Integer.toString(complaint.fromDbId())))).complete();
} }
});
/** Removes every complaint about one client. */
void deleteAll(int targetDbId) throws Exception {
conn.socket().executeCommand(new SingleCommand("complaindelall", ProtocolRole.CLIENT,
new CommandSingleParameter("tcldbid", Integer.toString(targetDbId)))).complete();
} }
} }
@@ -2,11 +2,14 @@ package eu.lixko.ts3j.client.net;
import com.github.manevolent.ts3j.event.*; import com.github.manevolent.ts3j.event.*;
import com.github.manevolent.ts3j.api.TextMessageTargetMode; import com.github.manevolent.ts3j.api.TextMessageTargetMode;
import eu.lixko.ts3j.client.audio.VoiceOutput;
import eu.lixko.ts3j.client.chat.ChatScope;
import eu.lixko.ts3j.client.contacts.Contact; import eu.lixko.ts3j.client.contacts.Contact;
import eu.lixko.ts3j.client.sound.SoundEvent; import eu.lixko.ts3j.client.sound.SoundEvent;
import eu.lixko.ts3j.client.sound.SoundNotifier; import eu.lixko.ts3j.client.sound.SoundNotifier;
import java.util.Map; import java.util.Map;
import java.util.Objects;
/** /**
* The {@link TS3Listener} side of a connection: keeps {@link ServerModel} in sync with * The {@link TS3Listener} side of a connection: keeps {@link ServerModel} in sync with
@@ -36,27 +39,11 @@ final class ConnectionEventHandler implements TS3Listener {
@Override @Override
public void onClientJoin(ClientJoinEvent e) { public void onClientJoin(ClientJoinEvent e) {
ClientEntry c = conn.getModel().putClient(e.getClientId(), e.getClientNickname(), e.getClientTargetId()); ClientEntry c = conn.getModel().putClient(e.getClientId(), e.getClientNickname(), e.getClientTargetId());
c.type = safeInt(e, "client_type"); applyClientProperties(c, e);
c.talkPower = e.getClientTalkPower();
c.talkRequest = talkRequested(e);
c.phoneticNickname = TeamspeakConnection.orEmpty(e.get("client_nickname_phonetic"));
c.inputMuted = e.isClientInputMuted();
c.outputMuted = e.isClientOutputMuted();
c.inputHardware = e.isClientUsingHardwareInput();
c.outputHardware = e.isClientUsingHardwareOutput();
c.away = e.isClientAway();
c.awayMessage = TeamspeakConnection.orEmpty(e.get("client_away_message"));
c.uniqueId = TeamspeakConnection.orEmpty(e.getUniqueClientIdentifier());
c.avatarFlag = TeamspeakConnection.orEmpty(e.get("client_flag_avatar"));
c.country = TeamspeakConnection.orEmpty(e.get("client_country"));
c.databaseId = e.getClientDatabaseId();
c.serverGroupIds = parseIntList(e.getClientServerGroups());
c.channelGroupId = e.getClientChannelGroupId();
c.unreadMessages = safeInt(e, "client_unread_messages");
c.self = (e.getClientId() == conn.getSelfClientId()); c.self = (e.getClientId() == conn.getSelfClientId());
// Query clients stay out of sight, as they do in the tree and in TS3's log. // Query clients stay out of sight, as they do in the tree and in TS3's log.
if (!c.self && !c.isQuery()) { if (!c.self && !c.isQuery()) {
conn.applyContact(c); conn.contacts.apply(c);
announceClientEntered(e); announceClientEntered(e);
logClientEntered(e); logClientEntered(e);
} }
@@ -69,12 +56,13 @@ final class ConnectionEventHandler implements TS3Listener {
if (e.getClientId() == conn.getSelfClientId()) { if (e.getClientId() == conn.getSelfClientId()) {
announceOwnRemoval(safeInt(e, "reasonid"), e); announceOwnRemoval(safeInt(e, "reasonid"), e);
} else if (gone == null || !gone.isQuery()) { } else if (gone == null || !gone.isQuery()) {
String name = conn.clientLink(e.getClientId()); String name = conn.announce.clientLink(e.getClientId());
announceClientLeft(e); announceClientLeft(e);
logClientLeft(e, name); logClientLeft(e, name);
} }
conn.getModel().removeClient(e.getClientId()); conn.getModel().removeClient(e.getClientId());
if (conn.getPlayback() != null) conn.getPlayback().removeClient(e.getClientId()); VoiceOutput playback = conn.own.playback();
if (playback != null) playback.removeClient(e.getClientId());
conn.ui.onModelChanged(); conn.ui.onModelChanged();
} }
@@ -90,7 +78,7 @@ final class ConnectionEventHandler implements TS3Listener {
logOwnMove(e, from, e.getTargetChannelId()); logOwnMove(e, from, e.getTargetChannelId());
} else if (!c.isQuery()) { } else if (!c.isQuery()) {
announceClientMoved(safeInt(e, "reasonid"), e.getClientId(), from, e.getTargetChannelId()); announceClientMoved(safeInt(e, "reasonid"), e.getClientId(), from, e.getTargetChannelId());
logClientMoved(e, conn.clientLink(c.id), from, e.getTargetChannelId()); logClientMoved(e, conn.announce.clientLink(c.id), from, e.getTargetChannelId());
} }
conn.ui.onModelChanged(); conn.ui.onModelChanged();
} }
@@ -98,25 +86,25 @@ final class ConnectionEventHandler implements TS3Listener {
/** A client became visible to us, logged the way native TS3's server tab does. */ /** A client became visible to us, logged the way native TS3's server tab does. */
private void logClientEntered(ClientJoinEvent e) { private void logClientEntered(ClientJoinEvent e) {
String name = conn.clientLink(e.getClientId(), String name = conn.announce.clientLink(e.getClientId(),
TeamspeakConnection.orEmpty(e.getUniqueClientIdentifier()), e.getClientNickname()); TeamspeakConnection.orEmpty(e.getUniqueClientIdentifier()), e.getClientNickname());
// A client connecting also comes with "switched", only from no channel at all. // A client connecting also comes with "switched", only from no channel at all.
int reason = safeInt(e, "reasonid"); int reason = safeInt(e, "reasonid");
if (reason == REASON_SWITCHED && e.getClientFromId() == 0) reason = -1; if (reason == REASON_SWITCHED && e.getClientFromId() == 0) reason = -1;
switch (reason) { switch (reason) {
case REASON_MOVED: case REASON_MOVED:
conn.log(name + " appears, coming from channel \"" + conn.channelLink(e.getClientFromId()) + "\""); conn.announce.log(name + " appears, coming from channel \"" + conn.announce.channelLink(e.getClientFromId()) + "\"");
break; break;
case REASON_CHANNEL_KICK: case REASON_CHANNEL_KICK:
conn.log(name + " appears, was kicked from channel \"" + conn.channelLink(e.getClientFromId()) conn.announce.log(name + " appears, was kicked from channel \"" + conn.announce.channelLink(e.getClientFromId())
+ "\" by " + invokerName(e)); + "\" by " + invokerName(e));
break; break;
case REASON_SWITCHED: case REASON_SWITCHED:
conn.log(name + " switched to channel \"" + conn.channelLink(e.getClientTargetId()) conn.announce.log(name + " switched to channel \"" + conn.announce.channelLink(e.getClientTargetId())
+ "\", coming from channel \"" + conn.channelLink(e.getClientFromId()) + "\""); + "\", coming from channel \"" + conn.announce.channelLink(e.getClientFromId()) + "\"");
break; break;
default: default:
conn.log(name + " connected to channel \"" + conn.channelLink(e.getClientTargetId()) + "\""); conn.announce.log(name + " connected to channel \"" + conn.announce.channelLink(e.getClientTargetId()) + "\"");
} }
} }
@@ -129,26 +117,26 @@ final class ConnectionEventHandler implements TS3Listener {
if (reason == REASON_SWITCHED && e.getClientTargetId() == 0) reason = -1; if (reason == REASON_SWITCHED && e.getClientTargetId() == 0) reason = -1;
switch (reason) { switch (reason) {
case REASON_TIMEOUT: case REASON_TIMEOUT:
conn.log(name + " dropped (ping timeout)"); conn.announce.log(name + " dropped (ping timeout)");
break; break;
case REASON_SERVER_KICK: case REASON_SERVER_KICK:
conn.log(name + " was kicked from the server by " + invokerName(e) + suffix); conn.announce.log(name + " was kicked from the server by " + invokerName(e) + suffix);
break; break;
case REASON_BAN: case REASON_BAN:
conn.log(name + " was banned from the server by " + invokerName(e) + suffix); conn.announce.log(name + " was banned from the server by " + invokerName(e) + suffix);
break; break;
case REASON_CHANNEL_KICK: case REASON_CHANNEL_KICK:
conn.log(name + " left: was kicked to channel \"" + conn.channelLink(e.getClientTargetId()) conn.announce.log(name + " left: was kicked to channel \"" + conn.announce.channelLink(e.getClientTargetId())
+ "\" by " + invokerName(e) + suffix); + "\" by " + invokerName(e) + suffix);
break; break;
case REASON_MOVED: case REASON_MOVED:
conn.log(name + " left, heading to channel \"" + conn.channelLink(e.getClientTargetId()) + "\""); conn.announce.log(name + " left, heading to channel \"" + conn.announce.channelLink(e.getClientTargetId()) + "\"");
break; break;
case REASON_SWITCHED: case REASON_SWITCHED:
conn.log(name + " left, switched to channel \"" + conn.channelLink(e.getClientTargetId()) + "\""); conn.announce.log(name + " left, switched to channel \"" + conn.announce.channelLink(e.getClientTargetId()) + "\"");
break; break;
default: default:
conn.log(name + " disconnected"); conn.announce.log(name + " disconnected");
} }
} }
@@ -158,16 +146,16 @@ final class ConnectionEventHandler implements TS3Listener {
String suffix = reasonMsg.isEmpty() ? "" : " (" + reasonMsg + ")"; String suffix = reasonMsg.isEmpty() ? "" : " (" + reasonMsg + ")";
switch (safeInt(e, "reasonid")) { switch (safeInt(e, "reasonid")) {
case REASON_MOVED: case REASON_MOVED:
conn.log(name + " was moved from channel \"" + conn.channelLink(fromChannel) + "\" to \"" conn.announce.log(name + " was moved from channel \"" + conn.announce.channelLink(fromChannel) + "\" to \""
+ conn.channelLink(toChannel) + "\" by " + invokerName(e)); + conn.announce.channelLink(toChannel) + "\" by " + invokerName(e));
break; break;
case REASON_CHANNEL_KICK: case REASON_CHANNEL_KICK:
conn.log(name + " was kicked from channel \"" + conn.channelLink(fromChannel) + "\" to \"" conn.announce.log(name + " was kicked from channel \"" + conn.announce.channelLink(fromChannel) + "\" to \""
+ conn.channelLink(toChannel) + "\" by " + invokerName(e) + suffix); + conn.announce.channelLink(toChannel) + "\" by " + invokerName(e) + suffix);
break; break;
default: default:
conn.log(name + " switched from channel \"" + conn.channelLink(fromChannel) + "\" to \"" conn.announce.log(name + " switched from channel \"" + conn.announce.channelLink(fromChannel) + "\" to \""
+ conn.channelLink(toChannel) + "\""); + conn.announce.channelLink(toChannel) + "\"");
} }
} }
@@ -177,16 +165,16 @@ final class ConnectionEventHandler implements TS3Listener {
String suffix = reasonMsg.isEmpty() ? "" : " (" + reasonMsg + ")"; String suffix = reasonMsg.isEmpty() ? "" : " (" + reasonMsg + ")";
switch (safeInt(e, "reasonid")) { switch (safeInt(e, "reasonid")) {
case REASON_MOVED: case REASON_MOVED:
conn.log("You were moved from channel \"" + conn.channelLink(fromChannel) + "\" to \"" conn.announce.log("You were moved from channel \"" + conn.announce.channelLink(fromChannel) + "\" to \""
+ conn.channelLink(toChannel) + "\" by " + invokerName(e)); + conn.announce.channelLink(toChannel) + "\" by " + invokerName(e));
break; break;
case REASON_CHANNEL_KICK: case REASON_CHANNEL_KICK:
conn.log("You were kicked from channel \"" + conn.channelLink(fromChannel) + "\" to \"" conn.announce.log("You were kicked from channel \"" + conn.announce.channelLink(fromChannel) + "\" to \""
+ conn.channelLink(toChannel) + "\" by " + invokerName(e) + suffix); + conn.announce.channelLink(toChannel) + "\" by " + invokerName(e) + suffix);
break; break;
default: default:
conn.log("You switched from channel \"" + conn.channelLink(fromChannel) + "\" to \"" conn.announce.log("You switched from channel \"" + conn.announce.channelLink(fromChannel) + "\" to \""
+ conn.channelLink(toChannel) + "\""); + conn.announce.channelLink(toChannel) + "\"");
} }
} }
@@ -197,23 +185,23 @@ final class ConnectionEventHandler implements TS3Listener {
private void announceClientEntered(ClientJoinEvent e) { private void announceClientEntered(ClientJoinEvent e) {
if (!conn.isConnected()) return; if (!conn.isConnected()) return;
int clientId = e.getClientId(); int clientId = e.getClientId();
boolean current = conn.inOwnChannel(e.getClientTargetId()); boolean current = conn.own.inOwnChannel(e.getClientTargetId());
Map<String, String> vars = conn.clientVars(clientId, e.getClientNickname()); Map<String, String> vars = conn.announce.clientVars(clientId, e.getClientNickname());
switch (safeInt(e, "reasonid")) { switch (safeInt(e, "reasonid")) {
case REASON_MOVED: case REASON_MOVED:
conn.sound(current ? SoundEvent.CLIENT_MOVED_TO_CURRENT_CHANNEL_APPEARS conn.announce.sound(current ? SoundEvent.CLIENT_MOVED_TO_CURRENT_CHANNEL_APPEARS
: SoundEvent.CLIENT_MOVED_TO_OTHER_CHANNEL_APPEARS, vars); : SoundEvent.CLIENT_MOVED_TO_OTHER_CHANNEL_APPEARS, vars);
break; break;
case REASON_CHANNEL_KICK: case REASON_CHANNEL_KICK:
conn.sound(current ? SoundEvent.CLIENT_WAS_KICKED_FROM_CHANNEL_TO_CURRENT_CHANNEL_APPEARS conn.announce.sound(current ? SoundEvent.CLIENT_WAS_KICKED_FROM_CHANNEL_TO_CURRENT_CHANNEL_APPEARS
: SoundEvent.CLIENT_WAS_KICKED_FROM_CHANNEL_TO_OTHER_CHANNEL_APPEARS, vars); : SoundEvent.CLIENT_WAS_KICKED_FROM_CHANNEL_TO_OTHER_CHANNEL_APPEARS, vars);
break; break;
case REASON_SWITCHED: case REASON_SWITCHED:
conn.sound(current ? SoundEvent.CLIENT_SWITCHED_TO_CURRENT_CHANNEL_APPEARS conn.announce.sound(current ? SoundEvent.CLIENT_SWITCHED_TO_CURRENT_CHANNEL_APPEARS
: SoundEvent.CLIENT_SWITCHED_TO_OTHER_CHANNEL_APPEARS, vars); : SoundEvent.CLIENT_SWITCHED_TO_OTHER_CHANNEL_APPEARS, vars);
break; break;
default: default:
conn.sound(current ? SoundEvent.CLIENT_CONNECTION_CONNECTED_CURRENT_CHANNEL conn.announce.sound(current ? SoundEvent.CLIENT_CONNECTION_CONNECTED_CURRENT_CHANNEL
: SoundEvent.CLIENT_CONNECTION_CONNECTED_SERVER, vars); : SoundEvent.CLIENT_CONNECTION_CONNECTED_SERVER, vars);
} }
} }
@@ -222,35 +210,35 @@ final class ConnectionEventHandler implements TS3Listener {
private void announceClientLeft(ClientLeaveEvent e) { private void announceClientLeft(ClientLeaveEvent e) {
if (!conn.isConnected()) return; if (!conn.isConnected()) return;
int clientId = e.getClientId(); int clientId = e.getClientId();
boolean current = conn.inOwnChannel(e.getClientFromId()); boolean current = conn.own.inOwnChannel(e.getClientFromId());
Map<String, String> vars = conn.clientVars(clientId, null); Map<String, String> vars = conn.announce.clientVars(clientId, null);
switch (safeInt(e, "reasonid")) { switch (safeInt(e, "reasonid")) {
case REASON_TIMEOUT: case REASON_TIMEOUT:
conn.sound(current ? SoundEvent.CLIENT_CONNECTION_LOST_CONNECTION_CURRENT_CHANNEL conn.announce.sound(current ? SoundEvent.CLIENT_CONNECTION_LOST_CONNECTION_CURRENT_CHANNEL
: SoundEvent.CLIENT_CONNECTION_LOST_CONNECTION_SERVER, vars); : SoundEvent.CLIENT_CONNECTION_LOST_CONNECTION_SERVER, vars);
break; break;
case REASON_SERVER_KICK: case REASON_SERVER_KICK:
conn.sound(current ? SoundEvent.CLIENT_WAS_KICKED_FROM_SERVER_CURRENT_CHANNEL conn.announce.sound(current ? SoundEvent.CLIENT_WAS_KICKED_FROM_SERVER_CURRENT_CHANNEL
: SoundEvent.CLIENT_WAS_KICKED_FROM_SERVER_SERVER, vars); : SoundEvent.CLIENT_WAS_KICKED_FROM_SERVER_SERVER, vars);
break; break;
case REASON_BAN: case REASON_BAN:
conn.sound(current ? SoundEvent.CLIENT_WAS_BANNED_CURRENT_CHANNEL conn.announce.sound(current ? SoundEvent.CLIENT_WAS_BANNED_CURRENT_CHANNEL
: SoundEvent.CLIENT_WAS_BANNED_SERVER, vars); : SoundEvent.CLIENT_WAS_BANNED_SERVER, vars);
break; break;
case REASON_CHANNEL_KICK: case REASON_CHANNEL_KICK:
conn.sound(current ? SoundEvent.CLIENT_WAS_KICKED_FROM_CHANNEL_FROM_CURRENT_CHANNEL_DISAPPEARS conn.announce.sound(current ? SoundEvent.CLIENT_WAS_KICKED_FROM_CHANNEL_FROM_CURRENT_CHANNEL_DISAPPEARS
: SoundEvent.CLIENT_WAS_KICKED_FROM_CHANNEL_TO_OTHER_CHANNEL_DISAPPEARS, vars); : SoundEvent.CLIENT_WAS_KICKED_FROM_CHANNEL_TO_OTHER_CHANNEL_DISAPPEARS, vars);
break; break;
case REASON_MOVED: case REASON_MOVED:
conn.sound(current ? SoundEvent.CLIENT_MOVED_FROM_CURRENT_CHANNEL_DISAPPEARS conn.announce.sound(current ? SoundEvent.CLIENT_MOVED_FROM_CURRENT_CHANNEL_DISAPPEARS
: SoundEvent.CLIENT_MOVED_TO_OTHER_CHANNEL_DISAPPEARS, vars); : SoundEvent.CLIENT_MOVED_TO_OTHER_CHANNEL_DISAPPEARS, vars);
break; break;
case REASON_SWITCHED: case REASON_SWITCHED:
conn.sound(current ? SoundEvent.CLIENT_SWITCHED_FROM_CURRENT_CHANNEL_DISAPPEARS conn.announce.sound(current ? SoundEvent.CLIENT_SWITCHED_FROM_CURRENT_CHANNEL_DISAPPEARS
: SoundEvent.CLIENT_SWITCHED_TO_OTHER_CHANNEL_DISAPPEARS, vars); : SoundEvent.CLIENT_SWITCHED_TO_OTHER_CHANNEL_DISAPPEARS, vars);
break; break;
default: default:
conn.sound(current ? SoundEvent.CLIENT_CONNECTION_DISCONNECTED_CURRENT_CHANNEL conn.announce.sound(current ? SoundEvent.CLIENT_CONNECTION_DISCONNECTED_CURRENT_CHANNEL
: SoundEvent.CLIENT_CONNECTION_DISCONNECTED_SERVER, vars); : SoundEvent.CLIENT_CONNECTION_DISCONNECTED_SERVER, vars);
} }
} }
@@ -258,22 +246,22 @@ final class ConnectionEventHandler implements TS3Listener {
/** A client we can see moved between two channels we can see ("stays"). */ /** A client we can see moved between two channels we can see ("stays"). */
private void announceClientMoved(int reason, int clientId, int fromChannel, int toChannel) { private void announceClientMoved(int reason, int clientId, int fromChannel, int toChannel) {
if (!conn.isConnected()) return; if (!conn.isConnected()) return;
boolean toCurrent = conn.inOwnChannel(toChannel); boolean toCurrent = conn.own.inOwnChannel(toChannel);
boolean fromCurrent = conn.inOwnChannel(fromChannel); boolean fromCurrent = conn.own.inOwnChannel(fromChannel);
Map<String, String> vars = conn.clientVars(clientId, null); Map<String, String> vars = conn.announce.clientVars(clientId, null);
switch (reason) { switch (reason) {
case REASON_MOVED: case REASON_MOVED:
conn.sound(toCurrent ? SoundEvent.CLIENT_MOVED_TO_CURRENT_CHANNEL_STAYS conn.announce.sound(toCurrent ? SoundEvent.CLIENT_MOVED_TO_CURRENT_CHANNEL_STAYS
: fromCurrent ? SoundEvent.CLIENT_MOVED_FROM_CURRENT_CHANNEL_STAYS : fromCurrent ? SoundEvent.CLIENT_MOVED_FROM_CURRENT_CHANNEL_STAYS
: SoundEvent.CLIENT_MOVED_TO_OTHER_CHANNEL_STAYS, vars); : SoundEvent.CLIENT_MOVED_TO_OTHER_CHANNEL_STAYS, vars);
break; break;
case REASON_CHANNEL_KICK: case REASON_CHANNEL_KICK:
conn.sound(toCurrent ? SoundEvent.CLIENT_WAS_KICKED_FROM_CHANNEL_TO_CURRENT_CHANNEL_STAYS conn.announce.sound(toCurrent ? SoundEvent.CLIENT_WAS_KICKED_FROM_CHANNEL_TO_CURRENT_CHANNEL_STAYS
: fromCurrent ? SoundEvent.CLIENT_WAS_KICKED_FROM_CHANNEL_FROM_CURRENT_CHANNEL_STAYS : fromCurrent ? SoundEvent.CLIENT_WAS_KICKED_FROM_CHANNEL_FROM_CURRENT_CHANNEL_STAYS
: SoundEvent.CLIENT_WAS_KICKED_FROM_CHANNEL_TO_OTHER_CHANNEL_STAYS, vars); : SoundEvent.CLIENT_WAS_KICKED_FROM_CHANNEL_TO_OTHER_CHANNEL_STAYS, vars);
break; break;
default: default:
conn.sound(toCurrent ? SoundEvent.CLIENT_SWITCHED_TO_CURRENT_CHANNEL_STAYS conn.announce.sound(toCurrent ? SoundEvent.CLIENT_SWITCHED_TO_CURRENT_CHANNEL_STAYS
: fromCurrent ? SoundEvent.CLIENT_SWITCHED_FROM_CURRENT_CHANNEL_STAYS : fromCurrent ? SoundEvent.CLIENT_SWITCHED_FROM_CURRENT_CHANNEL_STAYS
: SoundEvent.CLIENT_SWITCHED_TO_OTHER_CHANNEL_STAYS, vars); : SoundEvent.CLIENT_SWITCHED_TO_OTHER_CHANNEL_STAYS, vars);
} }
@@ -282,16 +270,16 @@ final class ConnectionEventHandler implements TS3Listener {
/** We changed channel ourselves, or somebody changed it for us. */ /** We changed channel ourselves, or somebody changed it for us. */
private void announceOwnMove(int reason, ClientMovedEvent e) { private void announceOwnMove(int reason, ClientMovedEvent e) {
if (!conn.isConnected()) return; if (!conn.isConnected()) return;
Map<String, String> vars = conn.channelVars(e.getTargetChannelId(), e.get("invokername")); Map<String, String> vars = conn.announce.channelVars(e.getTargetChannelId(), e.get("invokername"));
switch (reason) { switch (reason) {
case REASON_MOVED: case REASON_MOVED:
conn.sound(SoundEvent.YOU_WERE_MOVED_TO_DIFFERENT_CHANNEL, vars); conn.announce.sound(SoundEvent.YOU_WERE_MOVED_TO_DIFFERENT_CHANNEL, vars);
break; break;
case REASON_CHANNEL_KICK: case REASON_CHANNEL_KICK:
conn.sound(SoundEvent.YOU_WERE_KICKED_FROM_CHANNEL, vars); conn.announce.sound(SoundEvent.YOU_WERE_KICKED_FROM_CHANNEL, vars);
break; break;
default: default:
conn.sound(SoundEvent.YOU_SWITCHED_CHANNEL, vars); conn.announce.sound(SoundEvent.YOU_SWITCHED_CHANNEL, vars);
} }
} }
@@ -303,9 +291,9 @@ final class ConnectionEventHandler implements TS3Listener {
"clientname", TeamspeakConnection.orEmpty(e.get("invokername")), "clientname", TeamspeakConnection.orEmpty(e.get("invokername")),
"reason", TeamspeakConnection.orEmpty(e.get("reasonmsg"))); "reason", TeamspeakConnection.orEmpty(e.get("reasonmsg")));
if (reason == REASON_SERVER_KICK) { if (reason == REASON_SERVER_KICK) {
conn.sound(SoundEvent.YOU_WERE_KICKED_FROM_SERVER, vars); conn.announce.sound(SoundEvent.YOU_WERE_KICKED_FROM_SERVER, vars);
} else if (reason == REASON_BAN) { } else if (reason == REASON_BAN) {
conn.sound(SoundEvent.YOU_WERE_BANNED, vars); conn.announce.sound(SoundEvent.YOU_WERE_BANNED, vars);
} }
} }
@@ -313,9 +301,37 @@ final class ConnectionEventHandler implements TS3Listener {
public void onClientChanged(ClientUpdatedEvent e) { public void onClientChanged(ClientUpdatedEvent e) {
ClientEntry c = conn.getModel().getClient(e.getClientId()); ClientEntry c = conn.getModel().getClient(e.getClientId());
if (c == null) return; if (c == null) return;
boolean renamed = has(e, "client_nickname") && !e.get("client_nickname").equals(c.nickname);
String oldName = c.nickname; String oldName = c.nickname;
if (renamed) c.nickname = e.get("client_nickname"); int unreadBefore = c.unreadMessages;
applyClientProperties(c, e);
boolean renamed = !Objects.equals(c.nickname, oldName);
// The answers to clientgetvariables and to a description request.
if (reported(e, "client_description") || has(e, "client_version") || has(e, "client_platform")) {
conn.ui.onInfoUpdated();
}
if (reported(e, "client_myteamspeak_id") && !c.self && !c.isQuery()) conn.contacts.apply(c);
if (has(e, "client_unread_messages") && c.id == conn.getSelfClientId()) conn.unreadMessagesChanged(unreadBefore);
announceClientUpdate(e, c, renamed, oldName);
conn.ui.onModelChanged();
}
/**
* The properties a client event carries that the model keeps; each only when present, so
* the full set a client enters with and a partial update share one mapping.
*/
private static void applyClientProperties(ClientEntry c, BaseEvent e) {
if (has(e, "client_nickname")) c.nickname = e.get("client_nickname");
if (reported(e, "client_nickname_phonetic")) {
c.phoneticNickname = TeamspeakConnection.orEmpty(e.get("client_nickname_phonetic"));
}
if (reported(e, "client_unique_identifier")) {
c.uniqueId = TeamspeakConnection.orEmpty(e.get("client_unique_identifier"));
}
if (reported(e, "client_myteamspeak_id")) c.myTeamSpeakId = TeamspeakConnection.orEmpty(e.get("client_myteamspeak_id"));
if (has(e, "client_database_id")) c.databaseId = safeInt(e, "client_database_id");
if (has(e, "client_type")) c.type = safeInt(e, "client_type");
if (has(e, "client_servergroups")) c.serverGroupIds = parseIntList(e.get("client_servergroups"));
if (has(e, "client_channel_group_id")) c.channelGroupId = safeInt(e, "client_channel_group_id");
if (has(e, "client_input_muted")) c.inputMuted = e.getBoolean("client_input_muted"); if (has(e, "client_input_muted")) c.inputMuted = e.getBoolean("client_input_muted");
if (has(e, "client_output_muted")) c.outputMuted = e.getBoolean("client_output_muted"); if (has(e, "client_output_muted")) c.outputMuted = e.getBoolean("client_output_muted");
if (has(e, "client_input_hardware")) c.inputHardware = e.getBoolean("client_input_hardware"); if (has(e, "client_input_hardware")) c.inputHardware = e.getBoolean("client_input_hardware");
@@ -328,62 +344,51 @@ final class ConnectionEventHandler implements TS3Listener {
} else if (reported(e, "client_away_message")) { } else if (reported(e, "client_away_message")) {
c.awayMessage = TeamspeakConnection.orEmpty(e.get("client_away_message")); c.awayMessage = TeamspeakConnection.orEmpty(e.get("client_away_message"));
} }
if (has(e, "client_talk_power")) c.talkPower = e.getInt("client_talk_power"); if (has(e, "client_talk_power")) c.talkPower = safeInt(e, "client_talk_power");
if (has(e, "client_talk_request")) c.talkRequest = talkRequested(e); if (has(e, "client_talk_request")) applyTalkRequest(c, e);
if (reported(e, "client_nickname_phonetic")) { if (has(e, "client_is_talker")) c.talker = e.getBoolean("client_is_talker");
c.phoneticNickname = TeamspeakConnection.orEmpty(e.get("client_nickname_phonetic")); if (has(e, "client_is_channel_commander")) c.channelCommander = e.getBoolean("client_is_channel_commander");
} if (reported(e, "client_description")) c.description = TeamspeakConnection.orEmpty(e.get("client_description"));
if (reported(e, "client_description")) {
c.description = TeamspeakConnection.orEmpty(e.get("client_description"));
conn.ui.onInfoUpdated();
}
// The answer to clientgetvariables.
if (has(e, "client_version") || has(e, "client_platform")) {
if (has(e, "client_version")) c.version = e.get("client_version"); if (has(e, "client_version")) c.version = e.get("client_version");
if (has(e, "client_platform")) c.platform = e.get("client_platform"); if (has(e, "client_platform")) c.platform = e.get("client_platform");
conn.ui.onInfoUpdated();
}
if (has(e, "client_month_bytes_downloaded"))
c.monthBytesDownloaded = TeamspeakConnection.safeLong(e, "client_month_bytes_downloaded");
if (has(e, "client_month_bytes_uploaded"))
c.monthBytesUploaded = TeamspeakConnection.safeLong(e, "client_month_bytes_uploaded");
if (has(e, "client_is_channel_commander"))
c.channelCommander = e.getBoolean("client_is_channel_commander");
if (reported(e, "client_flag_avatar")) c.avatarFlag = TeamspeakConnection.orEmpty(e.get("client_flag_avatar")); if (reported(e, "client_flag_avatar")) c.avatarFlag = TeamspeakConnection.orEmpty(e.get("client_flag_avatar"));
if (reported(e, "client_country")) c.country = TeamspeakConnection.orEmpty(e.get("client_country")); if (reported(e, "client_country")) c.country = TeamspeakConnection.orEmpty(e.get("client_country"));
if (has(e, "client_unread_messages")) { if (has(e, "client_month_bytes_downloaded")) {
int before = c.unreadMessages; c.monthBytesDownloaded = TeamspeakConnection.safeLong(e, "client_month_bytes_downloaded");
c.unreadMessages = safeInt(e, "client_unread_messages");
if (c.id == conn.getSelfClientId()) conn.unreadMessagesChanged(before);
} }
announceClientUpdate(e, c, renamed, oldName); if (has(e, "client_month_bytes_uploaded")) {
conn.ui.onModelChanged(); c.monthBytesUploaded = TeamspeakConnection.safeLong(e, "client_month_bytes_uploaded");
}
if (has(e, "client_unread_messages")) c.unreadMessages = safeInt(e, "client_unread_messages");
} }
/** Renames, talk-power changes and recording flags all arrive as a client update. */ /** Renames, talk-power changes and recording flags all arrive as a client update. */
private void announceClientUpdate(ClientUpdatedEvent e, ClientEntry c, boolean renamed, String oldName) { private void announceClientUpdate(ClientUpdatedEvent e, ClientEntry c, boolean renamed, String oldName) {
if (!conn.isConnected()) return; if (!conn.isConnected()) return;
boolean self = c.id == conn.getSelfClientId(); boolean self = c.id == conn.getSelfClientId();
Map<String, String> vars = conn.clientVars(c.id, null); Map<String, String> vars = conn.announce.clientVars(c.id, null);
if (renamed) { if (renamed) {
conn.sound(safeInt(e, "invokerid") == conn.getSelfClientId() conn.announce.sound(safeInt(e, "invokerid") == conn.getSelfClientId()
? SoundEvent.CLIENT_RENAMED_BY_YOU : SoundEvent.CLIENT_RENAMED_BY_OTHER, vars); ? SoundEvent.CLIENT_RENAMED_BY_YOU : SoundEvent.CLIENT_RENAMED_BY_OTHER, vars);
conn.log(oldName + " is now known as " + conn.clientLink(c.id)); conn.announce.log(oldName + " is now known as " + conn.announce.clientLink(c.id));
} }
if (has(e, "client_talk_request") && talkRequested(e) && !self) { if (has(e, "client_talk_request") && talkRequested(e) && !self) {
conn.sound(SoundEvent.CLIENT_REQUESTED_TALK_POWER, vars); conn.announce.sound(SoundEvent.CLIENT_REQUESTED_TALK_POWER, vars);
conn.announce.log(conn.announce.clientLink(c.id) + " requested talk power");
} }
if (self && has(e, "client_is_talker")) { // Leaving the channel drops the grant too, but without an invoker: that is no news.
conn.sound(e.getBoolean("client_is_talker") if (self && has(e, "client_is_talker") && has(e, "invokerid")) {
? SoundEvent.YOU_WERE_GRANTED_TALK_POWER : SoundEvent.YOU_WERE_REVOKED_TALK_POWER, vars); boolean granted = e.getBoolean("client_is_talker");
conn.announce.sound(granted ? SoundEvent.YOU_WERE_GRANTED_TALK_POWER : SoundEvent.YOU_WERE_REVOKED_TALK_POWER, vars);
conn.announce.log("Talk Power " + (granted ? "granted" : "revoked") + " by " + invokerName(e));
} }
if (!self && has(e, "client_is_recording")) { if (!self && has(e, "client_is_recording")) {
boolean recording = e.getBoolean("client_is_recording"); boolean recording = e.getBoolean("client_is_recording");
if (!recording) { if (!recording) {
conn.sound(SoundEvent.CLIENT_RECORDING_STOP, vars); conn.announce.sound(SoundEvent.CLIENT_RECORDING_STOP, vars);
} else { } else {
conn.sound(conn.inOwnChannel(c.channelId) conn.announce.sound(conn.own.inOwnChannel(c.channelId)
? SoundEvent.CLIENT_RECORDING_IN_CHANNEL : SoundEvent.CLIENT_RECORDING_START, vars); ? SoundEvent.CLIENT_RECORDING_IN_CHANNEL : SoundEvent.CLIENT_RECORDING_START, vars);
} }
} }
@@ -399,9 +404,9 @@ final class ConnectionEventHandler implements TS3Listener {
applyChannelProperties(node, e); applyChannelProperties(node, e);
conn.getModel().relinkChannel(cid, pid, order); conn.getModel().relinkChannel(cid, pid, order);
if (conn.isConnected()) { if (conn.isConnected()) {
conn.sound(byInvoker(e, SoundEvent.CHANNEL_CREATED_BY_YOU, SoundEvent.CHANNEL_CREATED_BY_OTHER, conn.announce.sound(byInvoker(e, SoundEvent.CHANNEL_CREATED_BY_YOU, SoundEvent.CHANNEL_CREATED_BY_OTHER,
SoundEvent.CHANNEL_CREATED_BY_OTHER), conn.channelVars(cid, e.get("invokername"))); SoundEvent.CHANNEL_CREATED_BY_OTHER), conn.announce.channelVars(cid, e.get("invokername")));
conn.log("Channel \"" + conn.channelLink(cid) + "\" was created by " + invokerName(e)); conn.announce.log("Channel \"" + conn.announce.channelLink(cid) + "\" was created by " + invokerName(e));
} }
conn.ui.onModelChanged(); conn.ui.onModelChanged();
} }
@@ -410,9 +415,9 @@ final class ConnectionEventHandler implements TS3Listener {
public void onChannelDeleted(ChannelDeletedEvent e) { public void onChannelDeleted(ChannelDeletedEvent e) {
int cid = e.getChannelId(); int cid = e.getChannelId();
if (conn.isConnected()) { if (conn.isConnected()) {
conn.sound(byInvoker(e, SoundEvent.CHANNEL_DELETED_BY_YOU, SoundEvent.CHANNEL_DELETED_BY_OTHER, conn.announce.sound(byInvoker(e, SoundEvent.CHANNEL_DELETED_BY_YOU, SoundEvent.CHANNEL_DELETED_BY_OTHER,
SoundEvent.CHANNEL_DELETED_BY_SERVER), conn.channelVars(cid, e.get("invokername"))); SoundEvent.CHANNEL_DELETED_BY_SERVER), conn.announce.channelVars(cid, e.get("invokername")));
conn.log("Channel \"" + conn.channelName(cid) + "\" was deleted by " + invokerName(e)); conn.announce.log("Channel \"" + conn.announce.channelName(cid) + "\" was deleted by " + invokerName(e));
} }
conn.getModel().removeChannel(cid); conn.getModel().removeChannel(cid);
conn.ui.onModelChanged(); conn.ui.onModelChanged();
@@ -434,26 +439,30 @@ final class ConnectionEventHandler implements TS3Listener {
// Sorting among the same siblings arrives here too, and TS3 announces it as an edit. // Sorting among the same siblings arrives here too, and TS3 announces it as an edit.
if (has(e, "channel_order")) conn.getModel().relinkChannel(ch.id, ch.parentId, e.getInt("channel_order")); if (has(e, "channel_order")) conn.getModel().relinkChannel(ch.id, ch.parentId, e.getInt("channel_order"));
if (conn.isConnected()) { if (conn.isConnected()) {
boolean current = conn.inOwnChannel(ch.id); boolean current = conn.own.inOwnChannel(ch.id);
conn.sound(current conn.announce.sound(current
? byInvoker(e, SoundEvent.CHANNEL_EDITED_CURRENT_BY_YOU, ? byInvoker(e, SoundEvent.CHANNEL_EDITED_CURRENT_BY_YOU,
SoundEvent.CHANNEL_EDITED_CURRENT_BY_OTHER, SoundEvent.CHANNEL_EDITED_CURRENT_BY_OTHER) SoundEvent.CHANNEL_EDITED_CURRENT_BY_OTHER, SoundEvent.CHANNEL_EDITED_CURRENT_BY_OTHER)
: byInvoker(e, SoundEvent.CHANNEL_EDITED_OTHER_BY_YOU, : byInvoker(e, SoundEvent.CHANNEL_EDITED_OTHER_BY_YOU,
SoundEvent.CHANNEL_EDITED_OTHER_BY_OTHER, SoundEvent.CHANNEL_EDITED_OTHER_BY_SERVER), SoundEvent.CHANNEL_EDITED_OTHER_BY_OTHER, SoundEvent.CHANNEL_EDITED_OTHER_BY_SERVER),
conn.channelVars(ch.id, e.get("invokername"))); conn.announce.channelVars(ch.id, e.get("invokername")));
conn.log("Channel \"" + conn.channelLink(ch.id) + "\" was edited by " + invokerName(e)); conn.announce.log("Channel \"" + conn.announce.channelLink(ch.id) + "\" was edited by " + invokerName(e));
} }
conn.ui.onModelChanged(); conn.ui.onModelChanged();
} }
/** The properties a channel event carries that the model keeps; each only when present. */ /** The properties a channel event carries that the model keeps; each only when present. */
private static void applyChannelProperties(ChannelNode ch, BaseEvent e) { private void applyChannelProperties(ChannelNode ch, BaseEvent e) {
if (has(e, "channel_name")) ch.name = e.get("channel_name"); if (has(e, "channel_name")) ch.name = e.get("channel_name");
if (has(e, "channel_flag_default") && e.getBoolean("channel_flag_default")) {
conn.getModel().setDefaultChannel(ch.id);
}
// An emptied topic arrives as a bare key, which has() would skip. // An emptied topic arrives as a bare key, which has() would skip.
if (reported(e, "channel_topic")) ch.topic = TeamspeakConnection.orEmpty(e.get("channel_topic")); if (reported(e, "channel_topic")) ch.topic = TeamspeakConnection.orEmpty(e.get("channel_topic"));
if (has(e, "channel_icon_id")) ch.iconId = TeamspeakConnection.safeLong(e, "channel_icon_id"); if (has(e, "channel_icon_id")) ch.iconId = TeamspeakConnection.safeLong(e, "channel_icon_id");
if (has(e, "channel_flag_password")) ch.hasPassword = e.getBoolean("channel_flag_password"); if (has(e, "channel_flag_password")) ch.hasPassword = e.getBoolean("channel_flag_password");
if (has(e, "channel_flag_permanent")) ch.permanent = e.getBoolean("channel_flag_permanent"); if (has(e, "channel_flag_permanent")) ch.permanent = e.getBoolean("channel_flag_permanent");
if (has(e, "channel_needed_talk_power")) ch.neededTalkPower = safeInt(e, "channel_needed_talk_power");
if (has(e, "channel_flag_maxclients_unlimited") && e.getBoolean("channel_flag_maxclients_unlimited")) { if (has(e, "channel_flag_maxclients_unlimited") && e.getBoolean("channel_flag_maxclients_unlimited")) {
ch.maxClients = -1; ch.maxClients = -1;
} else if (has(e, "channel_maxclients")) { } else if (has(e, "channel_maxclients")) {
@@ -471,7 +480,7 @@ final class ConnectionEventHandler implements TS3Listener {
ChannelNode ch = conn.getModel().getChannel(safeInt(e, "cid")); ChannelNode ch = conn.getModel().getChannel(safeInt(e, "cid"));
if (ch == null || !ch.descriptionLoaded) return; if (ch == null || !ch.descriptionLoaded) return;
ch.descriptionLoaded = false; ch.descriptionLoaded = false;
conn.requestChannelInfo(ch.id); conn.channels.requestInfo(ch.id);
} }
@Override @Override
@@ -482,10 +491,10 @@ final class ConnectionEventHandler implements TS3Listener {
int order = has(e, "order") ? e.getInt("order") : ch.order; int order = has(e, "order") ? e.getInt("order") : ch.order;
conn.getModel().relinkChannel(ch.id, parent, order); conn.getModel().relinkChannel(ch.id, parent, order);
if (conn.isConnected()) { if (conn.isConnected()) {
conn.sound(byInvoker(e, SoundEvent.CHANNEL_MOVED_BY_YOU, SoundEvent.CHANNEL_MOVED_BY_OTHER, conn.announce.sound(byInvoker(e, SoundEvent.CHANNEL_MOVED_BY_YOU, SoundEvent.CHANNEL_MOVED_BY_OTHER,
SoundEvent.CHANNEL_MOVED_BY_OTHER), conn.channelVars(ch.id, e.get("invokername"))); SoundEvent.CHANNEL_MOVED_BY_OTHER), conn.announce.channelVars(ch.id, e.get("invokername")));
String newParent = parent == 0 ? conn.getModel().getServerName() : conn.channelLink(parent); String newParent = parent == 0 ? conn.getModel().getServerName() : conn.announce.channelLink(parent);
conn.log("Channel \"" + conn.channelLink(ch.id) + "\" was moved by " + invokerName(e) conn.announce.log("Channel \"" + conn.announce.channelLink(ch.id) + "\" was moved by " + invokerName(e)
+ ", new parent channel is \"" + newParent + "\""); + ", new parent channel is \"" + newParent + "\"");
} }
conn.ui.onModelChanged(); conn.ui.onModelChanged();
@@ -513,8 +522,8 @@ final class ConnectionEventHandler implements TS3Listener {
if (has(e, "virtualserver_name")) conn.getModel().setServerName(e.get("virtualserver_name")); if (has(e, "virtualserver_name")) conn.getModel().setServerName(e.get("virtualserver_name"));
conn.getModel().putServerProperties(e.getMap()); conn.getModel().putServerProperties(e.getMap());
if (conn.isConnected()) { if (conn.isConnected()) {
conn.sound(byInvoker(e, SoundEvent.SERVER_EDITED_BY_YOU, SoundEvent.SERVER_EDITED_BY_OTHER, conn.announce.sound(byInvoker(e, SoundEvent.SERVER_EDITED_BY_YOU, SoundEvent.SERVER_EDITED_BY_OTHER,
SoundEvent.SERVER_EDITED_BY_OTHER), conn.serverVars()); SoundEvent.SERVER_EDITED_BY_OTHER), conn.announce.serverVars());
} }
conn.ui.onModelChanged(); conn.ui.onModelChanged();
} }
@@ -525,13 +534,13 @@ final class ConnectionEventHandler implements TS3Listener {
if (c != null) c.addServerGroup(e.getServerGroupId()); if (c != null) c.addServerGroup(e.getServerGroupId());
boolean self = e.getClientId() == conn.getSelfClientId(); boolean self = e.getClientId() == conn.getSelfClientId();
if (self) conn.requestSelfPowers(); if (self) conn.requestSelfPowers();
conn.sound(self conn.announce.sound(self
? byInvoker(e, SoundEvent.YOU_SERVERGROUP_ADDED_BY_USER, SoundEvent.YOU_SERVERGROUP_ADDED_BY_USER, ? byInvoker(e, SoundEvent.YOU_SERVERGROUP_ADDED_BY_USER, SoundEvent.YOU_SERVERGROUP_ADDED_BY_USER,
SoundEvent.YOU_SERVERGROUP_ADDED_BY_SERVER) SoundEvent.YOU_SERVERGROUP_ADDED_BY_SERVER)
: byInvoker(e, SoundEvent.CLIENT_SERVERGROUP_ADDED_BY_USER, : byInvoker(e, SoundEvent.CLIENT_SERVERGROUP_ADDED_BY_USER,
SoundEvent.CLIENT_SERVERGROUP_ADDED_BY_USER, SoundEvent.CLIENT_SERVERGROUP_ADDED_BY_SERVER), SoundEvent.CLIENT_SERVERGROUP_ADDED_BY_USER, SoundEvent.CLIENT_SERVERGROUP_ADDED_BY_SERVER),
groupVars(e.getClientId(), serverGroupName(e.getServerGroupId()))); groupVars(e.getClientId(), serverGroupName(e.getServerGroupId())));
conn.log(clientLogName(e.getClientId()) + " was added to server group \"" + serverGroupName(e.getServerGroupId()) conn.announce.log(clientLogName(e.getClientId()) + " was added to server group \"" + serverGroupName(e.getServerGroupId())
+ "\" by " + invokerName(e) + "."); + "\" by " + invokerName(e) + ".");
conn.ui.onModelChanged(); conn.ui.onModelChanged();
} }
@@ -543,13 +552,13 @@ final class ConnectionEventHandler implements TS3Listener {
if (c != null) c.removeServerGroup(e.getServerGroupId()); if (c != null) c.removeServerGroup(e.getServerGroupId());
boolean self = clientId == conn.getSelfClientId(); boolean self = clientId == conn.getSelfClientId();
if (self) conn.requestSelfPowers(); if (self) conn.requestSelfPowers();
conn.sound(self conn.announce.sound(self
? byInvoker(e, SoundEvent.YOU_SERVERGROUP_REMOVED_BY_USER, ? byInvoker(e, SoundEvent.YOU_SERVERGROUP_REMOVED_BY_USER,
SoundEvent.YOU_SERVERGROUP_REMOVED_BY_USER, SoundEvent.YOU_SERVERGROUP_REMOVED_BY_SERVER) SoundEvent.YOU_SERVERGROUP_REMOVED_BY_USER, SoundEvent.YOU_SERVERGROUP_REMOVED_BY_SERVER)
: byInvoker(e, SoundEvent.CLIENT_SERVERGROUP_REMOVED_BY_USER, : byInvoker(e, SoundEvent.CLIENT_SERVERGROUP_REMOVED_BY_USER,
SoundEvent.CLIENT_SERVERGROUP_REMOVED_BY_USER, SoundEvent.CLIENT_SERVERGROUP_REMOVED_BY_SERVER), SoundEvent.CLIENT_SERVERGROUP_REMOVED_BY_USER, SoundEvent.CLIENT_SERVERGROUP_REMOVED_BY_SERVER),
groupVars(clientId, serverGroupName(e.getServerGroupId()))); groupVars(clientId, serverGroupName(e.getServerGroupId())));
conn.log(clientLogName(clientId) + " was removed from server group \"" + serverGroupName(e.getServerGroupId()) conn.announce.log(clientLogName(clientId) + " was removed from server group \"" + serverGroupName(e.getServerGroupId())
+ "\" by " + invokerName(e) + "."); + "\" by " + invokerName(e) + ".");
conn.ui.onModelChanged(); conn.ui.onModelChanged();
} }
@@ -561,13 +570,13 @@ final class ConnectionEventHandler implements TS3Listener {
boolean self = e.getClientId() == conn.getSelfClientId(); boolean self = e.getClientId() == conn.getSelfClientId();
if (self) conn.requestSelfPowers(); if (self) conn.requestSelfPowers();
String groupName = conn.getModel().channelGroupName(e.getChannelGroupId()); String groupName = conn.getModel().channelGroupName(e.getChannelGroupId());
conn.sound(self conn.announce.sound(self
? byInvoker(e, SoundEvent.YOU_CHANNELGROUP_CHANGED_BY_USER, ? byInvoker(e, SoundEvent.YOU_CHANNELGROUP_CHANGED_BY_USER,
SoundEvent.YOU_CHANNELGROUP_CHANGED_BY_USER, SoundEvent.YOU_CHANNELGROUP_CHANGED_BY_SERVER) SoundEvent.YOU_CHANNELGROUP_CHANGED_BY_USER, SoundEvent.YOU_CHANNELGROUP_CHANGED_BY_SERVER)
: byInvoker(e, SoundEvent.CLIENT_CHANNELGROUP_CHANGED_BY_USER, : byInvoker(e, SoundEvent.CLIENT_CHANNELGROUP_CHANGED_BY_USER,
SoundEvent.CLIENT_CHANNELGROUP_CHANGED_BY_USER, SoundEvent.CLIENT_CHANNELGROUP_CHANGED_BY_SERVER), SoundEvent.CLIENT_CHANNELGROUP_CHANGED_BY_USER, SoundEvent.CLIENT_CHANNELGROUP_CHANGED_BY_SERVER),
groupVars(e.getClientId(), groupName)); groupVars(e.getClientId(), groupName));
conn.log("Channel group \"" + TeamspeakConnection.orEmpty(groupName) + "\" was assigned to " conn.announce.log("Channel group \"" + TeamspeakConnection.orEmpty(groupName) + "\" was assigned to "
+ clientLogName(e.getClientId()) + " by " + invokerName(e) + "."); + clientLogName(e.getClientId()) + " by " + invokerName(e) + ".");
conn.ui.onModelChanged(); conn.ui.onModelChanged();
} }
@@ -583,7 +592,7 @@ final class ConnectionEventHandler implements TS3Listener {
/** A client's name for a log line, as a link, falling back to its id once it has left. */ /** A client's name for a log line, as a link, falling back to its id once it has left. */
private String clientLogName(int clientId) { private String clientLogName(int clientId) {
return conn.clientLink(clientId); return conn.announce.clientLink(clientId);
} }
/** Picks the event variant matching who caused the change: us, another client, or the server. */ /** Picks the event variant matching who caused the change: us, another client, or the server. */
@@ -594,7 +603,7 @@ final class ConnectionEventHandler implements TS3Listener {
} }
private Map<String, String> groupVars(int clientId, String groupName) { private Map<String, String> groupVars(int clientId, String groupName) {
Map<String, String> vars = conn.clientVars(clientId, null); Map<String, String> vars = conn.announce.clientVars(clientId, null);
vars.put("groupname", TeamspeakConnection.orEmpty(groupName)); vars.put("groupname", TeamspeakConnection.orEmpty(groupName));
return vars; return vars;
} }
@@ -627,49 +636,49 @@ final class ConnectionEventHandler implements TS3Listener {
@Override @Override
public void onPermissionList(PermissionListEvent e) { public void onPermissionList(PermissionListEvent e) {
conn.getModel().putPermissionName(e.get("permname")); conn.getModel().permissions().putName(e.get("permname"));
} }
@Override @Override
public void onClientNeededPermissions(ClientNeededPermissionsEvent e) { public void onClientNeededPermissions(ClientNeededPermissionsEvent e) {
conn.getModel().putSelfPermissionValue(safeInt(e, "permid"), safeInt(e, "permvalue")); conn.getModel().permissions().putValue(safeInt(e, "permid"), safeInt(e, "permvalue"));
} }
@Override @Override
public void onTextMessage(TextMessageEvent e) { public void onTextMessage(TextMessageEvent e) {
if (e.getInvokerId() == conn.getSelfClientId()) return; // don't echo our own if (e.getInvokerId() == conn.getSelfClientId()) return; // don't echo our own
Contact contact = conn.contacts.find(e.getInvokerUniqueId()); Contact contact = conn.contacts.store().find(e.getInvokerUniqueId());
if (contact != null) { if (contact != null) {
boolean isPrivate = e.getTargetMode() == TextMessageTargetMode.CLIENT; boolean isPrivate = e.getTargetMode() == TextMessageTargetMode.CLIENT;
if (isPrivate ? contact.ignorePrivateMessages : contact.ignorePublicMessages) return; if (isPrivate ? contact.ignorePrivateMessages : contact.ignorePublicMessages) return;
} }
ConnectionListener.ChatScope scope; ChatScope scope;
SoundEvent notification; SoundEvent notification;
switch (e.getTargetMode()) { switch (e.getTargetMode()) {
case CLIENT: case CLIENT:
scope = ConnectionListener.ChatScope.PRIVATE; scope = ChatScope.PRIVATE;
notification = SoundEvent.CHAT_RECEIVED_MESSAGE_CLIENT; notification = SoundEvent.CHAT_RECEIVED_MESSAGE_CLIENT;
break; break;
case CHANNEL: case CHANNEL:
scope = ConnectionListener.ChatScope.CHANNEL; scope = ChatScope.CHANNEL;
notification = SoundEvent.CHAT_RECEIVED_MESSAGE_CHANNEL; notification = SoundEvent.CHAT_RECEIVED_MESSAGE_CHANNEL;
break; break;
default: default:
scope = ConnectionListener.ChatScope.SERVER; scope = ChatScope.SERVER;
notification = SoundEvent.CHAT_RECEIVED_MESSAGE_SERVER; notification = SoundEvent.CHAT_RECEIVED_MESSAGE_SERVER;
break; break;
} }
conn.persistIncomingChat(scope, e.getInvokerId(), e.getInvokerUniqueId(), e.getInvokerName(), e.getMessage()); conn.chatLog.received(scope, e.getInvokerId(), e.getInvokerUniqueId(), e.getInvokerName(), e.getMessage());
conn.sound(notification, conn.clientVars(e.getInvokerId(), e.getInvokerName())); conn.announce.sound(notification, conn.announce.clientVars(e.getInvokerId(), e.getInvokerName()));
conn.ui.onChat(scope, e.getInvokerId(), e.getInvokerUniqueId(), e.getInvokerName(), e.getMessage()); conn.ui.onChat(scope, e.getInvokerId(), e.getInvokerUniqueId(), e.getInvokerName(), e.getMessage());
} }
@Override @Override
public void onClientPoke(ClientPokeEvent e) { public void onClientPoke(ClientPokeEvent e) {
Contact contact = conn.contacts.find(e.getInvokerUniqueId()); Contact contact = conn.contacts.store().find(e.getInvokerUniqueId());
if (contact != null && contact.ignorePokes) return; if (contact != null && contact.ignorePokes) return;
conn.sound(SoundEvent.OTHER_RECEIVED_POKE, conn.clientVars(e.getInvokerId(), e.getInvokerName())); conn.announce.sound(SoundEvent.OTHER_RECEIVED_POKE, conn.announce.clientVars(e.getInvokerId(), e.getInvokerName()));
String from = conn.contacts.displayName(e.getInvokerUniqueId(), TeamspeakConnection.orEmpty(e.getInvokerName())); String from = conn.contacts.store().displayName(e.getInvokerUniqueId(), TeamspeakConnection.orEmpty(e.getInvokerName()));
conn.ui.onPoke(from, TeamspeakConnection.orEmpty(e.get("msg"))); conn.ui.onPoke(from, TeamspeakConnection.orEmpty(e.get("msg")));
} }
@@ -691,7 +700,7 @@ final class ConnectionEventHandler implements TS3Listener {
private String invokerName(BaseEvent e) { private String invokerName(BaseEvent e) {
String name = TeamspeakConnection.orEmpty(e.get("invokername")); String name = TeamspeakConnection.orEmpty(e.get("invokername"));
if (name.isEmpty()) return "the server"; if (name.isEmpty()) return "the server";
return conn.clientLink(safeInt(e, "invokerid"), return conn.announce.clientLink(safeInt(e, "invokerid"),
TeamspeakConnection.orEmpty(e.get("invokeruid")), name); TeamspeakConnection.orEmpty(e.get("invokeruid")), name);
} }
@@ -701,6 +710,12 @@ final class ConnectionEventHandler implements TS3Listener {
return v != null && !v.isBlank() && !v.trim().equals("0"); return v != null && !v.isBlank() && !v.trim().equals("0");
} }
private static void applyTalkRequest(ClientEntry c, BaseEvent e) {
c.talkRequest = talkRequested(e);
c.talkRequestTime = c.talkRequest ? TeamspeakConnection.safeLong(e, "client_talk_request") : 0;
c.talkRequestMessage = c.talkRequest ? TeamspeakConnection.orEmpty(e.get("client_talk_request_msg")) : "";
}
private static int safeInt(BaseEvent e, String key) { private static int safeInt(BaseEvent e, String key) {
try { try {
String v = e.get(key); String v = e.get(key);
@@ -1,16 +1,12 @@
package eu.lixko.ts3j.client.net; package eu.lixko.ts3j.client.net;
import eu.lixko.ts3j.client.chat.ChatScope;
import java.util.List; import java.util.List;
/** /** What a {@link TeamspeakConnection} tells its session; calls arrive on connection threads. */
* UI-facing callbacks fired by {@link TeamspeakConnection}. Implementations are
* responsible for marshalling to the Swing EDT.
*/
public interface ConnectionListener { public interface ConnectionListener {
/** Message scope for chat display. */
enum ChatScope {SERVER, CHANNEL, PRIVATE}
void onStatus(String status); void onStatus(String status);
void onConnected(); void onConnected();

Some files were not shown because too many files have changed in this diff Show More