-
Notifications
You must be signed in to change notification settings - Fork 125
Expand file tree
/
Copy pathNakamaClient.java
More file actions
247 lines (218 loc) · 8.64 KB
/
Copy pathNakamaClient.java
File metadata and controls
247 lines (218 loc) · 8.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
// Copyright 2026 The Terasology Foundation
// SPDX-License-Identifier: Apache-2.0
package org.destinationsol.game.chat;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.heroiclabs.nakama.AbstractSocketListener;
import com.heroiclabs.nakama.Channel;
import com.heroiclabs.nakama.ChannelType;
import com.heroiclabs.nakama.Client;
import com.heroiclabs.nakama.DefaultClient;
import com.heroiclabs.nakama.Session;
import com.heroiclabs.nakama.SocketClient;
import com.heroiclabs.nakama.api.ChannelMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicReference;
/**
* Lightweight Nakama integration for DestinationSol.
* Connects to a shared chat channel for cross-game messaging.
*
* Enable via: -Dnakama.enabled=true -Dnakama.host=192.168.x.x -Dnakama.playerName=Bob
*/
public class NakamaClient {
private static final Logger logger = LoggerFactory.getLogger(NakamaClient.class);
private static final String GAME_ID = "destinationsol";
private static final Map<String, String> GAME_PREFIXES;
static {
Map<String, String> m = new HashMap<>();
m.put("terasology", "TS");
m.put("destinationsol", "DS");
m.put("minecraft", "MC");
GAME_PREFIXES = Collections.unmodifiableMap(m);
}
private final NakamaConfig config;
private Client client;
private Session session;
private SocketClient socket;
private Channel channel;
// Thread-safe queue for incoming messages to be consumed on the game thread
private final ConcurrentLinkedQueue<String> incomingMessages = new ConcurrentLinkedQueue<>();
// Last received item link — consumed by Beam In
private final AtomicReference<JsonObject> lastItemLink = new AtomicReference<>();
public NakamaClient(NakamaConfig config) {
this.config = config;
}
/**
* Connect to Nakama and join the chat channel.
* Call during game startup.
*/
public void connect() {
if (!config.isEnabled()) {
logger.info("Nakama client disabled");
return;
}
try {
String deviceId = getOrCreateDeviceId();
client = new DefaultClient("defaultkey", config.getHost(), config.getGrpcPort(), false);
session = client.authenticateDevice(deviceId).get();
if (!config.getPlayerName().isEmpty()) {
client.updateAccount(session, null, config.getPlayerName()).get();
}
logger.info("Nakama: authenticated as {}", session.getUserId());
socket = client.createSocket(config.getHost(), config.getWsPort(), false);
socket.connect(session, new AbstractSocketListener() {
@Override
public void onChannelMessage(ChannelMessage message) {
handleIncomingMessage(message);
}
}).get();
channel = socket.joinChat(config.getChannel(), ChannelType.ROOM).get();
logger.info("Nakama: joined channel '{}'", config.getChannel());
} catch (Exception e) {
logger.warn("Nakama: connection failed, continuing without cross-game chat", e);
cleanup();
}
}
private void handleIncomingMessage(ChannelMessage message) {
try {
JsonObject content = JsonParser.parseString(message.getContent()).getAsJsonObject();
String game = content.has("game") ? content.get("game").getAsString() : "";
if (GAME_ID.equals(game)) {
return; // Echo filter
}
String player = content.has("player") ? content.get("player").getAsString() : "???";
String text = content.has("text") ? content.get("text").getAsString() : "";
String prefix = "[" + GAME_PREFIXES.getOrDefault(game,
game.toUpperCase().substring(0, Math.min(game.length(), 2))) + "]";
// Check for item link message
String type = content.has("type") ? content.get("type").getAsString() : "chat";
if ("item_link".equals(type)) {
lastItemLink.set(content);
String itemName = content.has("name") ? content.get("name").getAsString() : "???";
String formatted = prefix + " " + player + " beamed: [" + itemName + "]";
incomingMessages.add(formatted);
return;
}
String formatted = prefix + " " + player + ": " + text;
incomingMessages.add(formatted);
} catch (Exception e) {
logger.warn("Nakama: failed to parse incoming message", e);
}
}
/**
* Send a chat message. Called from the /say console command.
*/
public boolean sendMessage(String text) {
if (socket == null || channel == null) {
return false;
}
try {
String playerName = config.getPlayerName().isEmpty()
? session.getUserId().substring(0, 8)
: config.getPlayerName();
JsonObject content = new JsonObject();
content.addProperty("game", GAME_ID);
content.addProperty("player", playerName);
content.addProperty("text", text);
socket.writeChatMessage(channel.getId(), content.toString()).get();
return true;
} catch (Exception e) {
logger.warn("Nakama: failed to send message", e);
return false;
}
}
/**
* Send an item link to the Nakama channel.
*/
public boolean sendItemLink(String itemName, String description, float price) {
if (socket == null || channel == null) {
return false;
}
try {
String playerName = config.getPlayerName().isEmpty()
? session.getUserId().substring(0, 8)
: config.getPlayerName();
JsonObject content = new JsonObject();
content.addProperty("game", GAME_ID);
content.addProperty("player", playerName);
content.addProperty("type", "item_link");
content.addProperty("name", itemName);
content.addProperty("description", description);
content.addProperty("price", price);
socket.writeChatMessage(channel.getId(), content.toString()).get();
return true;
} catch (Exception e) {
logger.warn("Nakama: failed to send item link", e);
return false;
}
}
/**
* Consume the last received item link (returns null if none pending).
* Once consumed, the same link cannot be consumed again.
*/
public JsonObject consumeItemLink() {
return lastItemLink.getAndSet(null);
}
/**
* Check if there's a pending item link without consuming it.
*/
public boolean hasItemLink() {
return lastItemLink.get() != null;
}
/**
* Poll for incoming messages. Call from the game loop.
* Returns null if no messages are pending.
*/
public String pollMessage() {
return incomingMessages.poll();
}
public boolean isConnected() {
return socket != null && channel != null;
}
public void disconnect() {
cleanup();
}
private void cleanup() {
if (socket != null) {
try { socket.disconnect(); } catch (Exception ignored) { }
socket = null;
}
channel = null;
session = null;
client = null;
}
private String getOrCreateDeviceId() {
String id = System.getProperty("nakama.deviceId", "");
if (!id.isEmpty()) {
return id;
}
Path idFile = Paths.get(System.getProperty("user.home"), ".bifrost", "device-id");
try {
if (Files.exists(idFile)) {
id = new String(Files.readAllBytes(idFile), StandardCharsets.UTF_8).trim();
if (!id.isEmpty()) {
return id;
}
}
id = UUID.randomUUID().toString();
Files.createDirectories(idFile.getParent());
Files.write(idFile, id.getBytes(StandardCharsets.UTF_8));
logger.info("Nakama: created device ID {}", id);
} catch (IOException e) {
id = UUID.randomUUID().toString();
logger.warn("Nakama: could not persist device ID, using ephemeral {}", id);
}
return id;
}
}