-
-
Notifications
You must be signed in to change notification settings - Fork 295
/
HumanController.java
318 lines (290 loc) · 13.2 KB
/
HumanController.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
package net.citizensnpcs.npc.entity;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.Callable;
import java.util.concurrent.LinkedBlockingDeque;
import net.citizensnpcs.Settings.Setting;
import net.citizensnpcs.api.CitizensAPI;
import net.citizensnpcs.api.event.DespawnReason;
import net.citizensnpcs.api.npc.NPC;
import net.citizensnpcs.api.util.Colorizer;
import net.citizensnpcs.api.util.Messaging;
import net.citizensnpcs.npc.AbstractEntityController;
import net.citizensnpcs.util.NMS;
import net.minecraft.server.v1_8_R1.PlayerInteractManager;
import net.minecraft.server.v1_8_R1.WorldServer;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.craftbukkit.v1_8_R1.CraftServer;
import org.bukkit.craftbukkit.v1_8_R1.CraftWorld;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.mojang.authlib.Agent;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.GameProfileRepository;
import com.mojang.authlib.HttpAuthenticationService;
import com.mojang.authlib.ProfileLookupCallback;
import com.mojang.authlib.minecraft.MinecraftSessionService;
import com.mojang.authlib.properties.Property;
import com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService;
import com.mojang.authlib.yggdrasil.YggdrasilMinecraftSessionService;
import com.mojang.authlib.yggdrasil.response.MinecraftProfilePropertiesResponse;
import com.mojang.util.UUIDTypeAdapter;
public class HumanController extends AbstractEntityController {
public HumanController() {
super();
if (SKIN_THREAD == null) {
Bukkit.getScheduler().runTaskTimerAsynchronously(CitizensAPI.getPlugin(), SKIN_THREAD = new SkinThread(),
10, 10);
}
}
@Override
protected Entity createEntity(final Location at, final NPC npc) {
final WorldServer nmsWorld = ((CraftWorld) at.getWorld()).getHandle();
String coloredName = Colorizer.parseColors(npc.getFullName());
if (coloredName.length() > 16) {
coloredName = coloredName.substring(0, 16);
}
UUID uuid = npc.getUniqueId();
if (uuid.version() == 4) { // clear version
long msb = uuid.getMostSignificantBits();
msb &= ~0x0000000000004000L;
msb |= 0x0000000000002000L;
uuid = new UUID(msb, uuid.getLeastSignificantBits());
}
GameProfile profile = new GameProfile(uuid, coloredName);
updateSkin(npc, nmsWorld, profile);
final EntityHumanNPC handle = new EntityHumanNPC(nmsWorld.getServer().getServer(), nmsWorld, profile,
new PlayerInteractManager(nmsWorld), npc);
handle.setPositionRotation(at.getX(), at.getY(), at.getZ(), at.getYaw(), at.getPitch());
Bukkit.getScheduler().scheduleSyncDelayedTask(CitizensAPI.getPlugin(), new Runnable() {
@Override
public void run() {
boolean removeFromPlayerList = Setting.REMOVE_PLAYERS_FROM_PLAYER_LIST.asBoolean();
NMS.addOrRemoveFromPlayerList(getBukkitEntity(),
npc.data().get("removefromplayerlist", removeFromPlayerList));
}
}, 1);
handle.getBukkitEntity().setSleepingIgnored(true);
NMS.sendPlayerlistPacket(true, null, handle.getBukkitEntity());
Bukkit.getScheduler().scheduleSyncDelayedTask(CitizensAPI.getPlugin(), new Runnable() {
@Override
public void run() {
// Double check that we're still spawned and haven't changed
// type.
if (npc.isSpawned() && npc.getEntity().getType() == EntityType.PLAYER) {
NMS.sendPlayerlistPacket(false, null, npc);
}
}
}, 2);
return handle.getBukkitEntity();
}
@Override
public Player getBukkitEntity() {
return (Player) super.getBukkitEntity();
}
@Override
public void remove() {
NMS.sendPlayerlistPacket(false, null, getBukkitEntity());
super.remove();
}
private void updateSkin(final NPC npc, final WorldServer nmsWorld, GameProfile profile) {
String skinUUID = npc.data().get(NPC.PLAYER_SKIN_UUID_METADATA);
if (skinUUID == null) {
skinUUID = npc.getName();
}
if (npc.data().has(CACHED_SKIN_UUID_METADATA)
&& npc.data().has(CACHED_SKIN_UUID_NAME_METADATA)
&& ChatColor.stripColor(skinUUID).equalsIgnoreCase(
ChatColor.stripColor(npc.data().<String> get(CACHED_SKIN_UUID_NAME_METADATA)))) {
skinUUID = npc.data().get(CACHED_SKIN_UUID_METADATA);
}
Property cached = TEXTURE_CACHE.get(skinUUID);
if (cached != null) {
profile.getProperties().put("textures", cached);
} else {
SKIN_THREAD.addRunnable(new SkinFetcher(new UUIDFetcher(skinUUID, npc), nmsWorld.getMinecraftServer().aB(),
npc));
}
}
private static class SkinFetcher implements Runnable {
private final NPC npc;
private final MinecraftSessionService repo;
private final Callable<String> uuid;
public SkinFetcher(Callable<String> uuid, MinecraftSessionService repo, NPC npc) {
this.uuid = uuid;
this.repo = repo;
this.npc = npc;
}
/*
* Yggdrasil's default implementation of this method silently fails instead of throwing an Exception like it should.
*/
private GameProfile fillProfileProperties(YggdrasilAuthenticationService auth, GameProfile profile,
boolean requireSecure) throws Exception {
URL url = HttpAuthenticationService.constantURL(new StringBuilder()
.append("https://sessionserver.mojang.com/session/minecraft/profile/")
.append(UUIDTypeAdapter.fromUUID(profile.getId())).toString());
url = HttpAuthenticationService.concatenateURL(url,
new StringBuilder().append("unsigned=").append(!requireSecure).toString());
MinecraftProfilePropertiesResponse response = (MinecraftProfilePropertiesResponse) MAKE_REQUEST.invoke(
auth, url, null, MinecraftProfilePropertiesResponse.class);
if (response == null) {
return profile;
}
GameProfile result = new GameProfile(response.getId(), response.getName());
result.getProperties().putAll(response.getProperties());
profile.getProperties().putAll(response.getProperties());
return result;
}
@Override
public void run() {
String realUUID;
try {
realUUID = uuid.call();
} catch (Exception e) {
return;
}
GameProfile skinProfile = null;
Property cached = TEXTURE_CACHE.get(realUUID);
if (cached != null) {
if (Messaging.isDebugging()) {
Messaging
.debug("Using cached skin texture for NPC " + npc.getName() + " UUID " + npc.getUniqueId());
}
skinProfile = new GameProfile(UUID.fromString(realUUID), "");
skinProfile.getProperties().put("textures", cached);
} else {
try {
skinProfile = fillProfileProperties(
((YggdrasilMinecraftSessionService) repo).getAuthenticationService(),
new GameProfile(UUID.fromString(realUUID), ""), true);
} catch (Exception e) {
if ((e.getMessage() != null && e.getMessage().contains("too many requests"))
|| (e.getCause() != null && e.getCause().getMessage() != null && e.getCause().getMessage()
.contains("too many requests"))) {
SKIN_THREAD.delay();
SKIN_THREAD.addRunnable(this);
}
return;
}
if (skinProfile == null || !skinProfile.getProperties().containsKey("textures"))
return;
Property textures = Iterables.getFirst(skinProfile.getProperties().get("textures"), null);
if (textures.getValue() == null || textures.getSignature() == null)
return;
if (Messaging.isDebugging()) {
Messaging.debug("Fetched skin texture for UUID " + realUUID + " for NPC " + npc.getName()
+ " UUID " + npc.getUniqueId());
}
TEXTURE_CACHE.put(realUUID, new Property("textures", textures.getValue(), textures.getSignature()));
}
Bukkit.getScheduler().callSyncMethod(CitizensAPI.getPlugin(), new Callable<Void>() {
@Override
public Void call() {
if (npc.isSpawned()) {
npc.despawn(DespawnReason.PENDING_RESPAWN);
npc.spawn(npc.getStoredLocation());
}
return null;
}
});
}
}
public static class SkinThread implements Runnable {
private volatile int delay = 0;
private volatile int retryTimes = 0;
private final BlockingDeque<Runnable> tasks = new LinkedBlockingDeque<Runnable>();
public void addRunnable(Runnable r) {
Iterator<Runnable> itr = tasks.iterator();
while (itr.hasNext()) {
if (((SkinFetcher) itr.next()).npc.getUniqueId().equals(((SkinFetcher) r).npc.getUniqueId())) {
itr.remove();
}
}
tasks.offer(r);
}
public void delay() {
delay = Setting.NPC_SKIN_RETRY_DELAY.asInt();
// need to wait before Mojang accepts API calls again
retryTimes++;
if (Setting.MAX_NPC_SKIN_RETRIES.asInt() >= 0 && retryTimes > Setting.MAX_NPC_SKIN_RETRIES.asInt()) {
tasks.clear();
retryTimes = 0;
}
}
@Override
public void run() {
if (delay > 0) {
delay--;
return;
}
Runnable r = tasks.pollFirst();
if (r == null) {
return;
}
r.run();
}
}
public static class UUIDFetcher implements Callable<String> {
private final NPC npc;
private String reportedUUID;
public UUIDFetcher(String reportedUUID, NPC npc) {
this.reportedUUID = reportedUUID;
this.npc = npc;
}
@Override
public String call() throws Exception {
String skinUUID = UUID_CACHE.get(reportedUUID);
if (skinUUID != null) {
npc.data().setPersistent(CACHED_SKIN_UUID_METADATA, skinUUID);
npc.data().setPersistent(CACHED_SKIN_UUID_NAME_METADATA, reportedUUID);
reportedUUID = skinUUID;
}
if (reportedUUID.contains("-")) {
return reportedUUID;
}
final GameProfileRepository repo = ((CraftServer) Bukkit.getServer()).getServer()
.getGameProfileRepository();
repo.findProfilesByNames(new String[] { ChatColor.stripColor(reportedUUID) }, Agent.MINECRAFT,
new ProfileLookupCallback() {
@Override
public void onProfileLookupFailed(GameProfile arg0, Exception arg1) {
}
@Override
public void onProfileLookupSucceeded(final GameProfile profile) {
UUID_CACHE.put(reportedUUID, profile.getId().toString());
if (Messaging.isDebugging()) {
Messaging.debug("Fetched UUID " + profile.getId() + " for NPC " + npc.getName()
+ " UUID " + npc.getUniqueId());
}
npc.data().setPersistent(CACHED_SKIN_UUID_METADATA, profile.getId().toString());
npc.data().setPersistent(CACHED_SKIN_UUID_NAME_METADATA, profile.getName());
}
});
return npc.data().get(CACHED_SKIN_UUID_METADATA, reportedUUID);
}
}
private static final String CACHED_SKIN_UUID_METADATA = "cached-skin-uuid";
private static final String CACHED_SKIN_UUID_NAME_METADATA = "cached-skin-uuid-name";
private static Method MAKE_REQUEST;
private static SkinThread SKIN_THREAD;
private static final Map<String, Property> TEXTURE_CACHE = Maps.newConcurrentMap();
private static final Map<String, String> UUID_CACHE = Maps.newConcurrentMap();
static {
try {
MAKE_REQUEST = YggdrasilAuthenticationService.class.getDeclaredMethod("makeRequest", URL.class,
Object.class, Class.class);
MAKE_REQUEST.setAccessible(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}