-
-
Notifications
You must be signed in to change notification settings - Fork 87
/
Copy pathFabricHuskHomes.java
393 lines (347 loc) · 13.2 KB
/
FabricHuskHomes.java
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
/*
* This file is part of HuskHomes, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <[email protected]>
* Copyright (c) contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.william278.huskhomes;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import net.fabricmc.api.DedicatedServerModInitializer;
import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.fabricmc.loader.api.FabricLoader;
import net.fabricmc.loader.api.ModContainer;
import net.kyori.adventure.audience.Audience;
//#if MC==12104
import net.kyori.adventure.platform.modcommon.MinecraftServerAudiences;
//#else
//$$ import net.kyori.adventure.platform.fabric.FabricServerAudiences;
//#endif
import net.minecraft.entity.Entity;
import net.minecraft.registry.RegistryKey;
import net.minecraft.registry.RegistryKeys;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.TeleportTarget;
import net.william278.desertwell.util.Version;
import net.william278.huskhomes.api.FabricHuskHomesAPI;
import net.william278.huskhomes.command.Command;
import net.william278.huskhomes.command.FabricCommand;
import net.william278.huskhomes.config.Locales;
import net.william278.huskhomes.config.Server;
import net.william278.huskhomes.config.Settings;
import net.william278.huskhomes.config.Spawn;
import net.william278.huskhomes.database.Database;
import net.william278.huskhomes.event.FabricEventDispatcher;
import net.william278.huskhomes.hook.FabricHookProvider;
import net.william278.huskhomes.hook.Hook;
import net.william278.huskhomes.listener.EventListener;
import net.william278.huskhomes.listener.FabricEventListener;
import net.william278.huskhomes.manager.Manager;
import net.william278.huskhomes.network.Broker;
import net.william278.huskhomes.network.FabricPluginMessage;
import net.william278.huskhomes.network.PluginMessageBroker;
import net.william278.huskhomes.position.Location;
import net.william278.huskhomes.position.Position;
import net.william278.huskhomes.position.World;
import net.william278.huskhomes.random.RandomTeleportEngine;
import net.william278.huskhomes.user.*;
import net.william278.huskhomes.util.FabricSavePositionProvider;
import net.william278.huskhomes.util.FabricTask;
import net.william278.huskhomes.util.UnsafeBlocks;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.spi.LoggingEventBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.function.Consumer;
import java.util.logging.Level;
@Getter
@NoArgsConstructor
public class FabricHuskHomes implements DedicatedServerModInitializer, HuskHomes, FabricTask.Supplier,
FabricEventDispatcher, FabricSavePositionProvider, FabricUserProvider, FabricHookProvider,
ServerPlayNetworking.PlayPayloadHandler<FabricPluginMessage> {
public static final Logger LOGGER = LoggerFactory.getLogger("HuskHomes");
private final ModContainer modContainer = FabricLoader.getInstance().getModContainer("huskhomes")
.orElseThrow(() -> new RuntimeException("Failed to get Mod Container"));
private final Map<String, Boolean> permissions = Maps.newHashMap();
//#if MC==12104
private MinecraftServerAudiences audiences;
//#else
//$$ private FabricServerAudiences audiences;
//#endif
private MinecraftServer minecraftServer;
private final Set<SavedUser> savedUsers = Sets.newHashSet();
private final Set<UUID> currentlyOnWarmup = Sets.newConcurrentHashSet();
private final Map<UUID, OnlineUser> onlineUserMap = Maps.newHashMap();
private final Map<String, List<User>> globalUserList = Maps.newConcurrentMap();
private final List<Command> commands = Lists.newArrayList();
@Setter
private Set<Hook> hooks = Sets.newHashSet();
@Setter
private Settings settings;
@Setter
private Locales locales;
@Setter
private Database database;
@Setter
private Manager manager;
@Setter
private EventListener eventListener;
@Setter
private RandomTeleportEngine randomTeleportEngine;
@Setter
private Spawn serverSpawn;
@Setter
private UnsafeBlocks unsafeBlocks;
@Setter
@Nullable
private Broker broker;
@Setter
@Nullable
private Server serverName;
@Override
public void onInitializeServer() {
this.load();
this.loadCommands();
ServerLifecycleEvents.SERVER_STARTING.register(this::onEnable);
ServerLifecycleEvents.SERVER_STOPPING.register(this::onDisable);
}
private void onEnable(@NotNull MinecraftServer server) {
this.minecraftServer = server;
//#if MC==12104
this.audiences = MinecraftServerAudiences.of(minecraftServer);
//#else
//$$ this.audiences = FabricServerAudiences.of(minecraftServer);
//#endif
this.enable();
}
private void onDisable(@NotNull MinecraftServer server) {
this.shutdown();
if (audiences != null) {
audiences.close();
audiences = null;
}
}
@Override
public void loadAPI() {
FabricHuskHomesAPI.register(this);
}
@Override
public void loadMetrics() {
// No metrics on Fabric
}
@Override
public void disablePlugin() {
onDisable(minecraftServer);
}
@Override
@NotNull
public ConsoleUser getConsole() {
return new ConsoleUser(audiences.console());
}
@NotNull
@Override
public Audience getAudience(@NotNull UUID user) {
return audiences.player(user);
}
@Override
public void setWorldSpawn(@NotNull Position position) {
final ServerWorld world = Adapter.adapt(position, minecraftServer);
if (world != null) {
world.setSpawnPos(
BlockPos.ofFloored(position.getX(), position.getY(), position.getZ()),
position.getYaw()
);
}
}
@Override
public Optional<Spawn> getServerSpawn() {
return Optional.ofNullable(serverSpawn);
}
@Override
@NotNull
public String getServerName() {
return serverName == null ? "server" : serverName.getName();
}
@Override
public boolean isDependencyAvailable(@NotNull String name) {
return FabricLoader.getInstance().isModLoaded(name);
}
@Override
@Nullable
public InputStream getResource(@NotNull String name) {
return this.modContainer.findPath(name)
.map(path -> {
try {
return Files.newInputStream(path);
} catch (IOException e) {
log(Level.WARNING, "Failed to load resource: " + name, e);
}
return null;
})
.orElse(this.getClass().getClassLoader().getResourceAsStream(name));
}
@Override
@NotNull
public Path getConfigDirectory() {
return FabricLoader.getInstance().getConfigDir().resolve("huskhomes");
}
@Override
@NotNull
public List<World> getWorlds() {
final List<World> worlds = Lists.newArrayList();
minecraftServer.getWorlds().forEach(world -> worlds.add(Adapter.adapt(world)));
return worlds;
}
@Override
@NotNull
public Version getPluginVersion() {
return Version.fromString(modContainer.getMetadata().getVersion().getFriendlyString(), "-");
}
@Override
@NotNull
public String getServerType() {
return String.format("fabric %s/%s", FabricLoader.getInstance()
.getModContainer("fabricloader").map(l -> l.getMetadata().getVersion().getFriendlyString())
.orElse("unknown"), minecraftServer.getVersion());
}
@Override
@NotNull
public Version getMinecraftVersion() {
return Version.fromString(minecraftServer.getVersion());
}
@Override
public void registerCommands(@NotNull List<Command> toRegister) {
CommandRegistrationCallback.EVENT.register((dispatcher, i1, i2) -> toRegister.stream().peek(commands::add)
.forEach((command) -> new FabricCommand(command, this).register(dispatcher)));
}
@Override
@NotNull
public EventListener createListener() {
return new FabricEventListener(this);
}
@Override
public Optional<Broker> getBroker() {
return Optional.ofNullable(broker);
}
@Override
public void setupPluginMessagingChannels() {
PayloadTypeRegistry.playC2S().register(FabricPluginMessage.CHANNEL_ID, FabricPluginMessage.CODEC);
PayloadTypeRegistry.playS2C().register(FabricPluginMessage.CHANNEL_ID, FabricPluginMessage.CODEC);
ServerPlayNetworking.registerGlobalReceiver(FabricPluginMessage.CHANNEL_ID, this);
}
// When the server receives a plugin message
@Override
public void receive(@NotNull FabricPluginMessage payload, @NotNull ServerPlayNetworking.Context context) {
if (broker instanceof PluginMessageBroker messenger
&& getSettings().getCrossServer().getBrokerType() == Broker.Type.PLUGIN_MESSAGE) {
messenger.onReceive(
PluginMessageBroker.BUNGEE_CHANNEL_ID,
getOnlineUser(context.player()),
payload.getData()
);
}
}
@Override
public void log(@NotNull Level level, @NotNull String message, @NotNull Throwable... exceptions) {
LoggingEventBuilder logEvent = LOGGER.makeLoggingEventBuilder(
switch (level.getName()) {
case "WARNING" -> org.slf4j.event.Level.WARN;
case "SEVERE" -> org.slf4j.event.Level.ERROR;
default -> org.slf4j.event.Level.INFO;
}
);
if (exceptions.length >= 1) {
logEvent = logEvent.setCause(exceptions[0]);
}
logEvent.log(message);
}
@Override
public void closeDatabase() {
if (database != null) {
database.close();
}
}
@Override
public void closeBroker() {
if (broker != null) {
broker.close();
}
}
@Override
@NotNull
public FabricHuskHomes getPlugin() {
return this;
}
public static class Adapter {
@NotNull
public static Location adapt(@NotNull Vec3d pos, @NotNull net.minecraft.world.World world,
float yaw, float pitch) {
return Position.at(
pos.getX(), pos.getY(), pos.getZ(),
yaw, pitch,
adapt(world)
);
}
@NotNull
public static Position adapt(@NotNull Vec3d pos, @NotNull net.minecraft.world.World world,
float yaw, float pitch, @NotNull String server) {
return Position.at(adapt(pos, world, yaw, pitch), server);
}
@NotNull
public static TeleportTarget adapt(@NotNull Location location, @NotNull MinecraftServer server,
@NotNull Consumer<Entity> runAfterTeleport) {
return new TeleportTarget(
adapt(location.getWorld(), server),
new Vec3d(location.getX(), location.getY(), location.getZ()),
Vec3d.ZERO,
location.getYaw(),
location.getPitch(),
runAfterTeleport::accept
);
}
@Nullable
public static ServerWorld adapt(@NotNull World world, @NotNull MinecraftServer server) {
return server.getWorld(RegistryKey.of(RegistryKeys.WORLD, Identifier.tryParse(world.getName())));
}
@Nullable
public static ServerWorld adapt(@NotNull Position position, @NotNull MinecraftServer server) {
return adapt(position.getWorld(), server);
}
@NotNull
public static World adapt(@NotNull net.minecraft.world.World world) {
return World.from(
world.getRegistryKey().getValue().asMinimalString(),
UUID.nameUUIDFromBytes(world.getRegistryKey().getValue().asString().getBytes())
);
}
}
}