forked from DFOnline/CodeClient
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtility.java
More file actions
317 lines (281 loc) · 12 KB
/
Copy pathUtility.java
File metadata and controls
317 lines (281 loc) · 12 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
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
package dev.dfonline.codeclient;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import dev.dfonline.codeclient.action.impl.GetActionDump;
import dev.dfonline.codeclient.hypercube.template.Template;
import net.minecraft.client.network.ClientPlayerEntity;
import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.nbt.NbtElement;
import net.minecraft.nbt.NbtList;
import net.minecraft.nbt.NbtString;
import net.minecraft.network.packet.c2s.play.CreativeInventoryActionC2SPacket;
import net.minecraft.sound.SoundCategory;
import net.minecraft.sound.SoundEvent;
import net.minecraft.text.MutableText;
import net.minecraft.text.Text;
import net.minecraft.text.TextColor;
import net.minecraft.util.Formatting;
import net.minecraft.util.Identifier;
import org.jetbrains.annotations.Nullable;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPOutputStream;
public class Utility {
/**
* Get the slot id to be used with a creative packet, from a local slot id.
*/
public static int getRemoteSlot(int slot) {
if (0 <= slot && slot <= 8) { // this is for the hotbar, which is after the inventory in packets.
return slot + 36;
} else return slot;
}
/**
* Be lazy, send your whole inventory!
*/
public static void sendInventory() {
if(CodeClient.MC.getNetworkHandler() == null || CodeClient.MC.player == null) return;
for (int i = 0; i <= 35; i++) {
CodeClient.MC.getNetworkHandler().sendPacket(new CreativeInventoryActionC2SPacket(getRemoteSlot(i), CodeClient.MC.player.getInventory().getStack(i)));
}
}
/**
* Ensure the player is holding an item, by holding and setting the first slot.
*
* @param item Any item
*/
public static void makeHolding(ItemStack item) {
if(CodeClient.MC.player == null) return;
PlayerInventory inv = CodeClient.MC.player.getInventory();
Utility.sendHandItem(item);
inv.selectedSlot = 0;
inv.setStack(0, item);
}
@SuppressWarnings("unused")
public static void debug(Object object) {
debug(Objects.toString(object));
}
public static void debug(String message) {
CodeClient.LOGGER.info("%%% DEBUG: {}", message);
}
/**
* Gets the base64 template data from an item. Null if there is none.
*/
public static String templateDataItem(ItemStack item) {
if (!item.hasNbt()) return null;
NbtCompound nbt = item.getNbt();
if (nbt == null) return null;
if (!nbt.contains("PublicBukkitValues")) return null;
NbtCompound publicBukkit = nbt.getCompound("PublicBukkitValues");
if (!publicBukkit.contains("hypercube:codetemplatedata")) return null;
String codeTemplateData = publicBukkit.getString("hypercube:codetemplatedata");
return JsonParser.parseString(codeTemplateData).getAsJsonObject().get("code").getAsString();
}
public static ItemStack makeTemplate(String message) {
ItemStack template = new ItemStack(Items.ENDER_CHEST);
NbtCompound nbt = new NbtCompound();
NbtCompound PublicBukkitValues = new NbtCompound();
PublicBukkitValues.putString("hypercube:codetemplatedata", "{\"author\":\"CodeClient\",\"name\":\"Template to be placed\",\"version\":1,\"code\":\"" + message + "\"}");
nbt.put("PublicBukkitValues", PublicBukkitValues);
template.setNbt(nbt);
return template;
}
/**
* Get the parsed Template from an item. None is the is none.
*/
public static Template templateItem(ItemStack item) {
String codeTemplateData = templateDataItem(item);
return Template.parse64(codeTemplateData);
}
public static void addLore(ItemStack stack, Text... lore) {
var display = Objects.requireNonNullElse(stack.getSubNbt("display"), new NbtCompound());
var loreList = new NbtList();
for (Text line : lore) loreList.add(Utility.textToNBT(Text.empty().append(line)));
display.put("Lore", loreList);
stack.setSubNbt("display", display);
}
public static void sendHandItem(ItemStack item) {
if(CodeClient.MC.getNetworkHandler() == null || CodeClient.MC.player == null) return;
CodeClient.MC.getNetworkHandler().sendPacket(new CreativeInventoryActionC2SPacket(36 + CodeClient.MC.player.getInventory().selectedSlot, item));
}
/**
* Gets all templates in the players inventory.
*/
public static List<ItemStack> templatesInInventory() {
if(CodeClient.MC.player == null) return null;
PlayerInventory inv = CodeClient.MC.player.getInventory();
ArrayList<ItemStack> templates = new ArrayList<>();
for (int i = 0; i < (27 + 9); i++) {
ItemStack item = inv.getStack(i);
if (!item.hasNbt()) continue;
NbtCompound nbt = item.getNbt();
if (nbt == null || !nbt.contains("PublicBukkitValues")) continue;
NbtCompound publicBukkit = nbt.getCompound("PublicBukkitValues");
if (!publicBukkit.contains("hypercube:codetemplatedata")) continue;
templates.add(item);
}
return templates;
}
public static String compileTemplate(JsonObject data) throws IOException {
return compileTemplate(data.getAsString());
}
/**
* GZIPs and base64's data for use in templates.
*
* @throws IOException If an I/O error happened with gzip
*/
public static String compileTemplate(String data) throws IOException {
ByteArrayOutputStream obj = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(obj);
gzip.write(data.getBytes());
gzip.close();
return new String(Base64.getEncoder().encode(obj.toByteArray()));
}
/**
* @deprecated This uses literals, use translations when you can.
*/
@Deprecated
public static void sendMessage(String message, ChatType type) {
sendMessage(Text.literal(message), type);
}
public static void sendMessage(Text message) {
sendMessage(message, ChatType.INFO);
}
public static void sendMessage(Text message, @Nullable ChatType type) {
ClientPlayerEntity player = CodeClient.MC.player;
if (player == null) return;
if (type == null) {
player.sendMessage(message, false);
} else {
player.sendMessage(Text.empty()
.append(type.getText())
.append(Text.literal(" "))
.append(message), false);
if (type == ChatType.FAIL) {
player.playSound(SoundEvent.of(new Identifier("minecraft:block.note_block.didgeridoo")), SoundCategory.PLAYERS, 2, 0);
}
}
}
/**
* Prepares a text object for use in an item's display tag
*
* @return Usable in lore and as a name in nbt.
*/
public static NbtString textToNBT(Text text) {
JsonElement json = Text.Serialization.toJsonTree(text);
if (json.isJsonObject()) {
JsonObject obj = (JsonObject) json;
if (!obj.has("color")) obj.addProperty("color", "white");
if (!obj.has("italic")) obj.addProperty("italic", false);
if (!obj.has("bold")) obj.addProperty("bold", false);
return NbtString.of(obj.toString());
} else return NbtString.of(json.toString());
}
/**
* Parses § formatted strings.
*
* @param text § formatted string.
* @return Text with all parsed text as siblings.
*/
public static MutableText textFromString(String text) {
MutableText output = Text.empty().setStyle(Text.empty().getStyle().withColor(TextColor.fromRgb(0xFFFFFF)).withItalic(false));
MutableText component = Text.empty();
Matcher m = Pattern.compile("§(([0-9a-kfmnolr])|x(§[0-9a-f]){6})|[^§]+").matcher(text);
while (m.find()) {
String data = m.group();
if (data.startsWith("§")) {
if (data.startsWith("§x")) {
component = component.setStyle(component.getStyle().withColor(Integer.valueOf(data.replaceAll("§x|§", ""), 16)));
} else {
component = component.formatted(Formatting.byCode(data.charAt(1)));
}
} else {
component.append(data);
output.append(component);
component = Text.empty().setStyle(component.getStyle());
}
}
return output;
}
public static boolean isGlitchStick(ItemStack item) {
if (item == null) return false;
NbtCompound nbt = item.getNbt();
if (nbt == null) return false;
if (nbt.isEmpty()) return false;
if (Objects.equals(nbt.getCompound("PublicBukkitValues").getString("hypercube:item_instance"), ""))
return false;
return Objects.equals(nbt.getCompound("display").getString("Name"), "{\"italic\":false,\"color\":\"red\",\"text\":\"Glitch Stick\"}");
}
public static HashMap<Integer, String> getBlockTagLines(ItemStack item) {
NbtCompound display = item.getSubNbt("display");
NbtList lore = (NbtList) display.get("Lore");
if (lore == null) throw new NullPointerException("Can't get lore.");
HashMap<Integer, String> options = new HashMap<>();
for (int index = lore.size() - 1; index >= 0; index--) {
NbtElement element = lore.get(index);
Text text = Text.Serialization.fromJson(element.asString());
var data = text.getString();
if (data.isBlank() || data.equals("Default Value:")) {
break;
}
options.put(index, data.replaceAll("» ", ""));
}
return options;
}
public static void textToString(Text content, StringBuilder build, GetActionDump.ColorMode colorMode) {
TextColor lastColor = null;
for (Text text : content.getSiblings()) {
TextColor color = text.getStyle().getColor();
if (color != null && (lastColor != color) && (colorMode != GetActionDump.ColorMode.NONE)) {
lastColor = color;
if (color.getName().contains("#")) {
build.append(String.join(colorMode.text, color.getName().split("")).replace("#", colorMode.text + "x").toLowerCase());
} else {
build.append(Formatting.valueOf(String.valueOf(color).toUpperCase()).toString().replace("§", colorMode.text));
}
}
build.append(text.getString());
}
}
public static String textToString(Text content) {
var builder = new StringBuilder();
textToString(content, builder, GetActionDump.ColorMode.SECTION);
return builder.toString();
}
/**
* Generate a string of 32 random A-Z,a-z,0-9 characters that are used for authentication tokens in the API.
* @return A random authentication token.
*/
public static String genAuthToken() {
SecureRandom random = new SecureRandom();
byte[] randomBytes = new byte[32];
random.nextBytes(randomBytes);
return HexFormat.of().formatHex(randomBytes);
}
/**
*
* Turns trimmed UUID (without dashes) into a UUID with dashes
* @return A UUID with dashes
*/
public static String fromTrimmed(String trimmedUUID) {
if (trimmedUUID == null)
throw new IllegalArgumentException();
StringBuilder builder = new StringBuilder(trimmedUUID.trim());
try {
builder.insert(20, "-");
builder.insert(16, "-");
builder.insert(12, "-");
builder.insert(8, "-");
} catch (StringIndexOutOfBoundsException e) {
throw new IllegalArgumentException();
}
return builder.toString();
}
}