-
-
Notifications
You must be signed in to change notification settings - Fork 170
/
SkinStorage.java
667 lines (565 loc) · 24 KB
/
SkinStorage.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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
/*
* SkinsRestorer
*
* Copyright (C) 2021 SkinsRestorer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
*/
package net.skinsrestorer.shared.storage;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import net.skinsrestorer.api.exception.SkinRequestException;
import net.skinsrestorer.api.interfaces.ISkinStorage;
import net.skinsrestorer.api.property.GenericProperty;
import net.skinsrestorer.api.property.IProperty;
import net.skinsrestorer.shared.exception.NotPremiumException;
import net.skinsrestorer.shared.utils.C;
import net.skinsrestorer.shared.utils.connections.MojangAPI;
import net.skinsrestorer.shared.utils.log.SRLogger;
import javax.sql.RowSet;
import java.io.*;
import java.nio.file.Files;
import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.TimeUnit;
@RequiredArgsConstructor
public class SkinStorage implements ISkinStorage {
private final SRLogger logger;
private final MojangAPI mojangAPI;
@Setter
private MySQL mysql;
private File skinsFolder;
private File playersFolder;
public void loadFolders(File pluginFolder) {
skinsFolder = new File(pluginFolder, "Skins");
//noinspection ResultOfMethodCallIgnored
skinsFolder.mkdirs();
playersFolder = new File(pluginFolder, "Players");
//noinspection ResultOfMethodCallIgnored
playersFolder.mkdirs();
}
public void preloadDefaultSkins() {
if (!Config.DEFAULT_SKINS_ENABLED)
return;
List<String> toRemove = new ArrayList<>();
Config.DEFAULT_SKINS.forEach(skin -> {
// TODO: add try for skinUrl
try {
if (!C.validUrl(skin)) {
getSkinForPlayer(skin);
}
} catch (SkinRequestException e) {
// removing skin from list
toRemove.add(skin);
logger.warning("[WARNING] DefaultSkin '" + skin + "'(.skin) could not be found or requested! Removing from list..");
logger.debug("[DEBUG] DefaultSkin '" + skin + "' error: ");
if (Config.DEBUG)
e.printStackTrace();
}
});
Config.DEFAULT_SKINS.removeAll(toRemove);
if (Config.DEFAULT_SKINS.isEmpty()) {
logger.warning("[WARNING] No more working DefaultSkin left... disabling feature");
Config.DEFAULT_SKINS_ENABLED = false;
}
}
/**
* This method seeks out a players actual skin (chosen or not) and returns
* either null (if no skin data found) or the property containing all
* the skin data.
* It also schedules a skin update to stay up to date with skin changes.
*
* @param playerName Player name to search skin for
* @throws SkinRequestException If MojangAPI lookup errors
*/
public IProperty getSkinForPlayer(final String playerName) throws SkinRequestException {
Optional<String> skin = getSkinName(playerName);
if (!skin.isPresent()) {
skin = Optional.of(playerName.toLowerCase());
}
Optional<IProperty> textures = getSkinData(skin.get());
if (!textures.isPresent()) {
// No cached skin found, get from MojangAPI, save and return
try {
if (!C.validMojangUsername(skin.get()))
throw new SkinRequestException(Locale.INVALID_PLAYER.replace("%player", skin.get()));
textures = mojangAPI.getSkin(skin.get());
if (!textures.isPresent())
throw new SkinRequestException(Locale.ERROR_NO_SKIN);
setSkinData(skin.get(), textures.get());
return textures.get();
} catch (SkinRequestException e) {
throw e;
} catch (Exception e) {
e.printStackTrace();
throw new SkinRequestException(Locale.WAIT_A_MINUTE);
}
} else {
return textures.get();
}
}
/**
* Returns a players custom skin.
*
* @param playerName the players name
* @return the custom skin name a player has set or null if not set
*/
public Optional<String> getSkinName(String playerName) {
playerName = playerName.toLowerCase();
if (Config.MYSQL_ENABLED) {
RowSet crs = mysql.query("SELECT * FROM " + Config.MYSQL_PLAYER_TABLE + " WHERE Nick=?", playerName);
if (crs != null)
try {
final String skin = crs.getString("Skin");
//maybe useless
if (skin.isEmpty()) {
removeSkin(playerName);
return Optional.empty();
}
return Optional.of(skin);
} catch (Exception e) {
e.printStackTrace();
}
} else {
playerName = removeForbiddenChars(playerName);
File playerFile = new File(playersFolder, playerName + ".player");
try {
if (!playerFile.exists())
return Optional.empty();
String skin = null;
try (BufferedReader buf = new BufferedReader(new FileReader(playerFile))) {
final String line = buf.readLine();
if (line != null)
skin = line;
}
// Maybe useless
if (skin == null) {
removeSkin(playerName);
return Optional.empty();
}
return Optional.of(skin);
} catch (IOException e) {
e.printStackTrace();
}
}
return Optional.empty();
}
/**
* Returns property object containing skin data of the wanted skin
*
* @param skinName Skin name
* @param updateOutdated On true, we update the skin if expired
*/
// #getSkinData() also create while we have #getSkinForPlayer()
public Optional<IProperty> getSkinData(String skinName, boolean updateOutdated) {
skinName = skinName.toLowerCase();
if (Config.MYSQL_ENABLED) {
RowSet crs = mysql.query("SELECT * FROM " + Config.MYSQL_SKIN_TABLE + " WHERE Nick=?", skinName);
if (crs != null)
try {
final String value = crs.getString("Value");
final String signature = crs.getString("Signature");
final String timestamp = crs.getString("timestamp");
return Optional.of(createProperty(skinName, updateOutdated, value, signature, timestamp));
} catch (Exception e) {
removeSkinData(skinName);
logger.info("Unsupported player format.. removing (" + skinName + ").");
}
} else {
skinName = removeWhitespaces(skinName);
skinName = removeForbiddenChars(skinName);
File skinFile = new File(skinsFolder, skinName + ".skin");
try {
if (!skinFile.exists())
return Optional.empty();
List<String> lines = Files.readAllLines(skinFile.toPath());
String value = lines.get(0);
String signature = lines.get(1);
String timestamp = lines.get(2);
return Optional.of(createProperty(skinName, updateOutdated, value, signature, timestamp));
} catch (Exception e) {
removeSkinData(skinName);
logger.info("Unsupported player format.. removing (" + skinName + ").");
}
}
return Optional.empty();
}
/**
* Create a platform specific property and also optionally update cached skin if outdated.
*
* @param playerName the players name
* @param updateOutdated whether the skin data shall be looked up again if the timestamp is too far away
* @param value skin data value
* @param signature signature to verify skin data
* @param timestamp time cached property data was created
* @return Platform specific property
* @throws SkinRequestException throws when no API calls were successful
*/
private IProperty createProperty(String playerName, boolean updateOutdated, String value, String signature, String timestamp) throws SkinRequestException {
if (updateOutdated && C.validMojangUsername(playerName) && isOld(Long.parseLong(timestamp))) {
Optional<IProperty> skin = mojangAPI.getSkin(playerName);
if (skin.isPresent()) {
setSkinData(playerName, skin.get());
return skin.get();
}
}
return mojangAPI.createProperty("textures", value, signature);
}
/**
* @see SkinStorage#getSkinData(String, boolean)
*/
public Optional<IProperty> getSkinData(String skinName) {
return getSkinData(skinName, true);
}
/**
* Checks if updating skins is disabled and if skin expired
*
* @param timestamp in milliseconds
* @return true if skin is outdated
*/
private boolean isOld(long timestamp) {
// Don't update if timestamp is not 0 or update is disabled.
if (timestamp == 0 || Config.DISALLOW_AUTO_UPDATE_SKIN)
return false;
return timestamp + TimeUnit.MINUTES.toMillis(Config.SKIN_EXPIRES_AFTER) <= System.currentTimeMillis();
}
/**
* Removes custom players skin name from database
*
* @param name - Players name
*/
public void removeSkin(String name) {
name = name.toLowerCase();
if (Config.MYSQL_ENABLED) {
mysql.execute("DELETE FROM " + Config.MYSQL_PLAYER_TABLE + " WHERE Nick=?", name);
} else {
name = removeForbiddenChars(name);
File playerFile = new File(playersFolder, name + ".player");
try {
Files.deleteIfExists(playerFile.toPath());
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Removes skin data from database
*
* @param skinName Skin name
*/
public void removeSkinData(String skinName) {
skinName = skinName.toLowerCase();
if (Config.MYSQL_ENABLED) {
mysql.execute("DELETE FROM " + Config.MYSQL_SKIN_TABLE + " WHERE Nick=?", skinName);
} else {
skinName = removeWhitespaces(skinName);
skinName = removeForbiddenChars(skinName);
File skinFile = new File(skinsFolder, skinName + ".skin");
try {
Files.deleteIfExists(skinFile.toPath());
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Saves custom player's skin name to database
*
* @param playerName Players name
* @param skinName Skin name
*/
public void setSkinName(String playerName, String skinName) {
playerName = playerName.toLowerCase();
if (Config.MYSQL_ENABLED) {
mysql.execute("INSERT INTO " + Config.MYSQL_PLAYER_TABLE + " (Nick, Skin) VALUES (?,?) ON DUPLICATE KEY UPDATE Skin=?",
playerName, skinName, skinName);
} else {
playerName = removeForbiddenChars(playerName);
File playerFile = new File(playersFolder, playerName + ".player");
try {
if (!playerFile.exists() && !playerFile.createNewFile())
throw new IOException("Could not create player file!");
try (FileWriter writer = new FileWriter(playerFile)) {
skinName = removeWhitespaces(skinName);
skinName = removeForbiddenChars(skinName);
writer.write(skinName);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Saves skin data to database
*
* @param skinName Skin name
* @param textures Property object
* @param timestamp timestamp string in millis
*/
public void setSkinData(String skinName, IProperty textures, String timestamp) {
skinName = skinName.toLowerCase();
String value = textures.getValue();
String signature = textures.getSignature();
if (Config.MYSQL_ENABLED) {
mysql.execute("INSERT INTO " + Config.MYSQL_SKIN_TABLE + " (Nick, Value, Signature, timestamp) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE Value=?, Signature=?, timestamp=?",
skinName, value, signature, timestamp, value, signature, timestamp);
} else {
skinName = removeWhitespaces(skinName);
skinName = removeForbiddenChars(skinName);
File skinFile = new File(skinsFolder, skinName + ".skin");
try {
if (value.isEmpty() || signature.isEmpty() || timestamp.isEmpty())
return;
if (!skinFile.exists() && !skinFile.createNewFile())
throw new IOException("Could not create skin file!");
try (FileWriter writer = new FileWriter(skinFile)) {
writer.write(value + "\n" + signature + "\n" + timestamp);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* @see SkinStorage#setSkinData(String, IProperty, String)
*/
public void setSkinData(String skinName, IProperty textures) {
setSkinData(skinName, textures, Long.toString(System.currentTimeMillis()));
}
// TODO: CUSTOM_GUI
// seems to be that crs order is ignored...
public Map<String, IProperty> getSkins(int number) {
//Using mysql
Map<String, IProperty> list = new TreeMap<>();
if (Config.MYSQL_ENABLED) {
String filterBy = "";
String orderBy = "Nick";
// custom gui
if (Config.CUSTOM_GUI_ENABLED) {
StringBuilder sb = new StringBuilder();
if (Config.CUSTOM_GUI_ONLY) {
Config.CUSTOM_GUI_SKINS.forEach(sb.append("|")::append);
filterBy = "WHERE Nick RLIKE '" + sb.substring(1) + "'";
} else {
Config.CUSTOM_GUI_SKINS.forEach(skin -> sb.append(", '").append(skin).append("'"));
orderBy = "FIELD(Nick" + sb + ") DESC, Nick";
}
}
RowSet crs = mysql.query("SELECT Nick, Value, Signature FROM " + Config.MYSQL_SKIN_TABLE + " " + filterBy + " ORDER BY " + orderBy);
int i = 0;
try {
do {
if (i >= number)
list.put(crs.getString("Nick").toLowerCase(), mojangAPI.createProperty("textures", crs.getString("Value"), crs.getString("Signature")));
i++;
} while (crs.next());
} catch (SQLException ignored) {
}
// When not using mysql
} else {
//filter out non "*.skin" files.
FilenameFilter skinFileFilter = (dir, name) -> name.endsWith(".skin");
String[] fileNames = skinsFolder.list(skinFileFilter);
if (fileNames == null)
// TODO: should this not also be null if no skin is valid?
return list;
Arrays.sort(fileNames);
int i = 0;
for (String file : fileNames) {
String skinName = file.replace(".skin", "");
if (i >= number) {
if (Config.CUSTOM_GUI_ONLY) { //Show only Config.CUSTOM_GUI_SKINS in the gui
for (String GuiSkins : Config.CUSTOM_GUI_SKINS) {
if (skinName.toLowerCase().contains(GuiSkins.toLowerCase()))
getSkinData(skinName, false).ifPresent(property -> list.put(skinName.toLowerCase(), property));
}
} else {
getSkinData(skinName, false).ifPresent(property -> list.put(skinName.toLowerCase(), property));
}
}
i++;
}
}
return list;
}
// TODO: remove duplicated code and use existing methods....
// TODO: needs a lot refactoring!
// TODO: We should _always_ return our own Property object and cast to the platform specific one just before actually setting the skin.
// TODO: That should save lots of duplicated code
public Map<String, GenericProperty> getSkinsRaw(int number) {
Map<String, GenericProperty> list = new TreeMap<>();
if (Config.MYSQL_ENABLED) {
RowSet crs = mysql.query("SELECT Nick, Value, Signature FROM " + Config.MYSQL_SKIN_TABLE + " ORDER BY `Nick`");
int i = 0;
int foundSkins = 0;
try {
do {
if (i >= number && foundSkins <= 26) {
GenericProperty prop = new GenericProperty();
prop.setName("textures");
prop.setValue(crs.getString("Value"));
prop.setSignature(crs.getString("Signature"));
list.put(crs.getString("Nick"), prop);
foundSkins++;
}
i++;
} while (crs.next());
} catch (SQLException ignored) {
}
} else {
// filter out non "*.skin" files.
FilenameFilter skinFileFilter = (dir, name) -> name.endsWith(".skin");
String[] fileNames = skinsFolder.list(skinFileFilter);
if (fileNames == null)
return list;
Arrays.sort(fileNames);
int i = 0;
int foundSkins = 0;
for (String file : fileNames) {
String skinName = file.replace(".skin", "");
File skinFile = new File(skinsFolder, file);
if (i >= number && foundSkins <= 26) {
try {
if (!skinFile.exists())
return null;
List<String> lines = Files.readAllLines(skinFile.toPath());
GenericProperty prop = new GenericProperty();
prop.setName("textures");
prop.setValue(lines.get(0));
prop.setSignature(lines.get(1));
list.put(skinName, prop);
foundSkins++;
} catch (Exception ignored) {
}
}
i++;
}
}
return list;
}
/**
* @param skinName Skin name
* @return true on updated
* @throws SkinRequestException On updating disabled OR invalid username + api error
*/
// skin update [include custom skin flag]
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public boolean updateSkinData(String skinName) throws SkinRequestException {
if (!C.validMojangUsername(skinName))
throw new SkinRequestException(Locale.ERROR_UPDATING_CUSTOMSKIN);
// Check if updating is disabled for skin (by timestamp = 0)
boolean updateDisabled = false;
if (Config.MYSQL_ENABLED) {
RowSet crs = mysql.query("SELECT timestamp FROM " + Config.MYSQL_SKIN_TABLE + " WHERE Nick=?", skinName);
if (crs != null)
try {
updateDisabled = crs.getString("timestamp").equals("0");
} catch (Exception ignored) {
}
} else {
skinName = removeWhitespaces(skinName);
skinName = removeForbiddenChars(skinName);
File skinFile = new File(skinsFolder, skinName + ".skin");
try {
if (skinFile.exists()) {
updateDisabled = Files.readAllLines(skinFile.toPath()).get(2).equals("0");
}
} catch (Exception ignored) {
}
}
if (updateDisabled)
throw new SkinRequestException(Locale.ERROR_UPDATING_CUSTOMSKIN);
// Update Skin
try {
Optional<String> mojangUUID = mojangAPI.getUUIDMojang(skinName);
if (mojangUUID.isPresent()) {
Optional<IProperty> textures = mojangAPI.getProfileMojang(mojangUUID.get());
if (textures.isPresent()) {
setSkinData(skinName, textures.get());
return true;
}
}
} catch (NotPremiumException e) {
throw new SkinRequestException(Locale.ERROR_UPDATING_CUSTOMSKIN);
}
return false;
}
/**
* @see SkinStorage#getDefaultSkinName(String, boolean)
*/
public String getDefaultSkinName(String playerName) {
return getDefaultSkinName(playerName, false);
}
/**
* Filters player name to exclude non [a-z_]
* Checks and process default skin.
* IF no default skin:
* 1: Return player if clear
* 2: Return skin if found
* Else: return player
*
* @param playerName Player name
* @param clear return player instead of his set skin
* @return setSkin or DefaultSkin, if player has no setSkin or default skin, we return his name
*/
public String getDefaultSkinName(String playerName, boolean clear) {
// LTrim and RTrim player name
playerName = playerName.replaceAll("^\\\\s+", "");
playerName = playerName.replaceAll("\\\\s+$", "");
if (Config.DEFAULT_SKINS_ENABLED) {
// don't return default skin name for premium players if enabled
if (!Config.DEFAULT_SKINS_PREMIUM) {
// check if player is premium
try {
if (C.validMojangUsername(playerName) && mojangAPI.getUUID(playerName) != null) {
// player is premium, return his skin name instead of default skin
return playerName;
}
} catch (SkinRequestException ignored) {
// Player is not premium catching exception here to continue returning a default skin name
}
}
// return default skin name if user has no custom skin set, or we want to clear to default
if (!getSkinName(playerName).isPresent() || clear) {
final List<String> skins = Config.DEFAULT_SKINS;
String randomSkin;
if (skins.size() > 1) {
randomSkin = skins.get(new Random().nextInt(skins.size()));
} else {
randomSkin = skins.get(0);
}
// return player name if there are no default skins set
return randomSkin != null ? randomSkin : playerName;
}
}
// return the player name if we want to clear the skin
if (clear)
return playerName;
// empty if player has no custom skin, we'll return his name then
return getSkinName(playerName).orElse(playerName);
}
private String removeForbiddenChars(String str) {
// Escape all Windows / Linux forbidden printable ASCII characters
return str.replaceAll("[\\\\/:*?\"<>|]", "·");
}
//todo remove all whitespace after last starting space.
private String removeWhitespaces(String str) {
// Remove all whitespace expect when startsWith " ".
if (str.startsWith(" ")) {
return str;
}
return str.replaceAll("\\s", "");
}
}