forked from Podshot/MCEdit-Unified
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathversion_utils.py
492 lines (450 loc) · 19.2 KB
/
version_utils.py
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
import json
import urllib2
from directories import userCachePath, getDataDir
import os
import time
import base64 # @UnusedImport
from pymclevel.mclevelbase import PlayerNotFound
import urllib
from PIL import Image
from urllib2 import HTTPError
import atexit
import threading
#def getPlayerSkinURL(uuid):
# try:
# playerJSONResponse = urllib2.urlopen('https://sessionserver.mojang.com/session/minecraft/profile/{}'.format(uuid))
# print playerJSONResponse
# texturesJSON = json.loads(playerJSONResponse)['properties']
# for prop in properties:
# if prop['name'] == 'textures':
# b64 = base64.b64decode(prop['value']);
# print b64
# return json.loads(b64)['textures']['SKIN']['url']
# except:
# raise
#print getPlayerSkinURL('4566e69fc90748ee8d71d7ba5aa00d20')
class __PlayerCache:
SUCCESS = 0
FAILED = 1
def __convert(self):
jsonFile = None
fp = open(userCachePath)
try:
jsonFile = json.load(fp)
fp.close()
except ValueError:
fp.close()
# Assuming JSON file is corrupted, deletes file and creates new one
os.remove(userCachePath)
with open(userCachePath, 'w') as json_out:
json.dump([], json_out)
if jsonFile is not None:
for old_player in jsonFile.keys():
player = jsonFile[old_player]
new_player = {"Playername": player["username"], "UUID (No Separator)": old_player.replace("-", ""),
"UUID (Separator)": old_player, "WasSuccessful": True, "Timstamp": player["timestamp"]}
self._playerCacheList.append(new_player)
self._save()
print "Convert usercache.json"
def fixAllOfPodshotsBugs(self):
for player in self._playerCacheList:
if "Timstamp" in player:
player["Timestamp"] = player["Timstamp"]
del player["Timstamp"]
self._save()
def __init__(self):
self._playerCacheList = []
if not os.path.exists(userCachePath):
out = open(userCachePath, 'w')
json.dump(self._playerCacheList, out)
out.close()
f = open(userCachePath, 'r')
line = f.readline()
if line.startswith("{"):
f.close()
self.__convert()
f.close()
try:
json_in = open(userCachePath)
self._playerCacheList = json.load(json_in)
except:
print "usercache.json is corrupted"
self._playerCacheList = []
finally:
json_in.close()
self.fixAllOfPodshotsBugs()
self.refresh_lock = threading.Lock()
self.player_refreshing = threading.Thread(target=self._refreshAll)
self.player_refreshing.daemon = True
self.player_refreshing.start()
#self._refreshAll()
def _save(self):
out = open(userCachePath, "wb")
json.dump(self._playerCacheList, out, indent=4, separators=(',', ':'))
out.close()
def _removePlayerWithName(self, name):
toRemove = None
for p in self._playerCacheList:
if p["Playername"] == name:
toRemove = p
if toRemove is not None:
self._playerCacheList.remove(toRemove)
self._save()
def _removePlayerWithUUID(self, uuid, seperator=True):
toRemove = None
for p in self._playerCacheList:
if seperator:
if p["UUID (Separator)"] == uuid:
toRemove = p
else:
if p["UUID (No Separator)"] == uuid:
toRemove = p
if toRemove is not None:
self._playerCacheList.remove(toRemove)
self._save()
def nameInCache(self, name):
isInCache = False
for p in self._playerCacheList:
if p["Playername"] == name:
isInCache = True
return isInCache
def uuidInCache(self, uuid, seperator=True):
isInCache = False
for p in self._playerCacheList:
if seperator:
if p["UUID (Separator)"] == uuid:
isInCache = True
else:
if p["UUID (No Separator)"] == uuid:
isInCache = True
return isInCache
def _refreshAll(self):
with self.refresh_lock:
playersNeededToBeRefreshed = []
try:
t = time.time()
except:
t = 0
for player in self._playerCacheList:
if player["Timestamp"] != "<Invalid>":
if t - player["Timestamp"] > 21600:
playersNeededToBeRefreshed.append(player)
for player in playersNeededToBeRefreshed:
self.getPlayerFromUUID(player["UUID (Separator)"], forceNetwork=True, dontSave=True)
self._save()
def force_refresh(self):
players = self._playerCacheList
for player in players:
self.getPlayerFromUUID(player["UUID (Separator)"], forceNetwork=True)
def getPlayerFromUUID(self, uuid, forceNetwork=False, dontSave=False):
player = {}
response = None
if forceNetwork:
if self.uuidInCache(uuid):
self._removePlayerWithUUID(uuid)
try:
response = urllib2.urlopen("https://sessionserver.mojang.com/session/minecraft/profile/{}".format(uuid.replace("-",""))).read()
except urllib2.URLError:
return uuid
if response is not None and response != "":
playerJSON = json.loads(response)
player["Playername"] = playerJSON["name"]
player["UUID (No Separator)"] = playerJSON["id"]
player["UUID (Separator)"] = uuid
player["WasSuccessful"] = True
player["Timestamp"] = time.time()
self._playerCacheList.append(player)
if not dontSave:
self._save()
return playerJSON["name"]
else:
return uuid
else:
couldNotFind = False
for p in self._playerCacheList:
if p["UUID (Separator)"] == uuid and p["WasSuccessful"]:
couldNotFind = False
return p["Playername"]
else:
couldNotFind = True
if couldNotFind:
result = self.getPlayerFromUUID(uuid, forceNetwork=True)
if result == uuid:
player = {"Playername":"<Unknown>","UUID (Separator)":uuid,"UUID (No Separator)":uuid.replace("-",""),"Timestamp":"<Invalid>","WasSuccessful":False}
self._playerCacheList.append(player)
return uuid
def getPlayerFromPlayername(self, playername, forceNetwork=False, separator=True):
response = None
if forceNetwork:
if self.nameInCache(playername):
self._removePlayerWithName(playername)
try:
response = urllib2.urlopen("https://api.mojang.com/users/profiles/minecraft/{}".format(playername)).read()
except urllib2.URLError:
return playername
if response is not None and response != "":
playerJSON = json.loads(response)
player = {"Playername": playername, "UUID (No Separator)": playerJSON["id"]}
uuid = playerJSON["id"][:8]+"-"+playerJSON["id"][8:12]+"-"+playerJSON["id"][12:16]+"-"+playerJSON["id"][16:20]+"-"+playerJSON["id"][20:]
player["UUID (Separator)"] = uuid
player["WasSuccessful"] = True
player["Timestamp"] = time.time()
self._playerCacheList.append(player)
self._save()
if separator:
return uuid
else:
return playerJSON["id"]
else:
return playername
else:
couldNotFind = False
for p in self._playerCacheList:
if p["Playername"] == playername and p["WasSuccessful"]:
couldNotFind = False
return p["UUID (Separator)"]
else:
couldNotFind = True
if couldNotFind:
result = self.getPlayerFromPlayername(playername, forceNetwork=True)
if result == playername:
player = {"Playername":playername,"UUID (Separator)":"<Unknown>","UUID (No Separator)":"<Unknown>","Timestamp":"<Invalid>","WasSuccessful":False}
self._playerCacheList.append(player)
return playername
# 0 if for a list of the playernames, 1 is for a dictionary of all player data
def getAllPlayersKnown(self, returnType=0, include_failed_lookups=False):
toReturn = None
if returnType == 0:
toReturn = []
for p in self._playerCacheList:
if p["WasSuccessful"]:
toReturn.append(p["Playername"])
elif include_failed_lookups:
toReturn.append(p["Playername"])
elif returnType == 1:
toReturn = {}
for p in self._playerCacheList:
if p["WasSuccessful"]:
toReturn[p["Playername"]] = p
elif include_failed_lookups:
toReturn[p["Playername"]] = p
return toReturn
def getPlayerInfo(self, playername):
response_name = None
response_uuid = None
player = {}
if self.nameInCache(playername):
self._removePlayerWithName(playername)
try:
response_name = json.loads(urllib2.urlopen("https://api.mojang.com/users/profiles/minecraft/{}".format(playername)).read())
response_uuid = json.loads(urllib2.urlopen("https://sessionserver.mojang.com/session/minecraft/profile/{}".format(response_name["id"])).read())
except urllib2.URLError:
return playername
if response_name is not None and response_name != "" and response_uuid is not None and response_uuid != "":
player["Playername"] = response_name["name"]
player["UUID (Separator)"] = response_name["id"][:8]+"-"+response_name["id"][8:12]+"-"+response_name["id"][12:16]+"-"+response_name["id"][16:20]+"-"+response_name["id"][20:]
player["UUID (No Separator)"] = response_name["id"]
player["WasSuccessful"] = True
player["Timestamp"] = time.time()
self._playerCacheList.append(player)
self._save()
return player["UUID (Separator)"], player["Playername"], player["UUID (No Separator)"]
else:
raise Exception("Couldn't find player")
@staticmethod
def __formats():
player = {
"Playername":"<Username>",
"UUID":"<uuid>",
"Timestamp":"<timestamp>",
# WasSuccessful will be true if the UUID/Player name was retrieved successfully
"WasSuccessful":True
}
pass
def cleanup(self):
remove = []
for player in self._playerCacheList:
if not player["WasSuccessful"]:
remove.append(player)
for toRemove in remove:
self._playerCacheList.remove(toRemove)
self._save()
playercache = __PlayerCache()
def getUUIDFromPlayerName(player, seperator=True, forceNetwork=False):
return playercache.getPlayerFromPlayername(player, forceNetwork, seperator)
'''
if forceNetwork:
try:
playerJSONResponse = urllib2.urlopen("https://api.mojang.com/users/profiles/minecraft/{}".format(player)).read()
playerJSON = json.loads(playerJSONResponse)
if seperator:
return "-".join((playerJSON["id"][:8], playerJSON["id"][8:12], playerJSON["id"][12:16], playerJSON["id"][16:20], playerJSON["id"][20:]))
else:
return playerJSON["id"]
except:
raise PlayerNotFound(player)
else:
try:
t = time.time()
except:
t = 0
try:
if not os.path.exists(userCachePath):
usercache = {}
print "{} doesn't exist, will not cache".format(userCachePath)
else:
try:
f = open(userCachePath,"r+")
usercache = json.loads(f.read())
except:
print "Error loading {} from disk".format(userCachePath)
os.remove(userCachePath)
f = open(userCachePath, 'ar+')
usercache = {}
try:
uuid = [x for x in usercache if usercache[x]["username"].lower() == player.lower()][0]
if os.path.exists(userCachePath) and uuid in usercache and "timestamp" in usercache[uuid] and t-usercache[uuid]["timestamp"] < 21600:
refreshUUID = False
else:
refreshUUID = True
except:
refreshUUID = True
if refreshUUID:
uuid = getUUIDFromPlayerName(player, seperator, True)
try:
usercache[uuid] = {"username":getPlayerNameFromUUID(uuid, True),"timestamp":t}
except:
print "Error updating {} from network. Using last known".format(uuid)
return uuid
try:
if os.path.exists(userCachePath):
f.seek(0)
f.write(json.dumps(usercache))
f.close()
except:
print "Error writing {} to disk".format(userCachePath)
return uuid
except:
print "Error getting the uuid for {}".format(player)
raise PlayerNotFound(player)
'''
def getPlayerNameFromUUID(uuid,forceNetwork=False):
'''
Gets the Username from a UUID
:param uuid: The Player's UUID
:param forceNetwork: Forces use Mojang's API instead of first looking in the usercache.json
'''
return playercache.getPlayerFromUUID(uuid, forceNetwork)
'''
if forceNetwork:
try:
nuuid = uuid.replace("-", "")
playerJSONResponse = urllib2.urlopen("https://api.mojang.com/user/profiles/{}/names".format(nuuid)).read()
playerJSON = json.loads(playerJSONResponse)
return playerJSON[0]
except:
raise PlayerNotFound(uuid)
else:
try:
t = time.time()
except:
t = 0
try:
if not os.path.exists(userCachePath):
usercache = {}
print "{} doesn't exist, will not cache".format(userCachePath)
else:
try:
f = open(userCachePath,"r+")
usercache = json.loads(f.read())
except:
print "Error loading {} from disk".format(userCachePath)
os.remove(userCachePath)
f = open(userCachePath, 'ar+')
usercache = {}
try:
if os.path.exists(userCachePath) and uuid in usercache and "timestamp" in usercache[uuid] and t-usercache[uuid]["timestamp"] < 21600:
refreshUUID = False
else:
refreshUUID = True
except:
refreshUUID = True
if refreshUUID:
try:
usercache[uuid] = {"username":getPlayerNameFromUUID(uuid,True),"timestamp":t}
except:
print "Error loading {} from network".format(uuid)
return uuid
try:
if os.path.exists(userCachePath):
f.seek(0)
f.write(json.dumps(usercache))
f.close()
except:
print "Error writing {} to disk".format(userCachePath)
try:
return usercache[uuid]["username"]
except:
print "Error returning uuid"
return uuid
except:
print "Error getting the username for {}".format(uuid)
return uuid
'''
def getPlayerSkin(uuid, force=False, trying_again=False, instance=None):
SKIN_URL = "http://skins.minecraft.net/MinecraftSkins/{}.png"
toReturn = 'char.png'
try:
os.mkdir("player-skins")
except OSError:
pass
if force or not os.path.exists(os.path.join("player-skins", uuid.replace("-", "_")+".png")):
try:
# Checks to see if the skin even exists
urllib2.urlopen(SKIN_URL.format(playercache.getPlayerFromUUID(uuid, forceNetwork=False)))
except urllib2.URLError as e:
if "Not Found" in e.msg:
return toReturn
try:
if os.path.exists(os.path.join("player-skins", uuid.replace("-", "_")+".png")) and not force:
player_skin = Image.open(os.path.join("player-skins", uuid.replace("-","_")+".png"))
if player_skin.size == (64,64):
player_skin = player_skin.crop((0,0,64,32))
player_skin.save(os.path.join("player-skins", uuid.replace("-","_")+".png"))
toReturn = os.path.join("player-skins", uuid.replace("-","_")+".png")
else:
playername = playercache.getPlayerFromUUID(uuid,forceNetwork=False)
urllib.urlretrieve(SKIN_URL.format(playername), os.path.join("player-skins", uuid.replace("-","_")+".png"))
toReturn = os.path.join("player-skins", uuid.replace("-","_")+".png")
player_skin = Image.open(toReturn)
if player_skin.size == (64,64):
player_skin = player_skin.crop((0,0,64,32))
player_skin.save(os.path.join("player-skins", uuid.replace("-","_")+".png"))
except IOError:
print "Couldn't find Image file ("+str(uuid.replace("-","_")+".png")+") or the file may be corrupted"
print "Trying to re-download skin...."
if not trying_again and instance is not None:
instance.delete_skin(uuid)
os.remove(os.path.join("player-skins", uuid.replace("-","_")+".png"))
toReturn = getPlayerSkin(uuid, force=True, trying_again=True)
pass
except HTTPError:
print "Couldn't connect to a network"
raise Exception("Could not connect to the skins server, please check your Internet connection and try again.")
pass
except Exception:
print "Unknown error occurred while reading/downloading skin for "+str(uuid.replace("-","_")+".png")
pass
return toReturn
def _cleanup():
if os.path.exists("player-skins"):
for image_file in os.listdir("player-skins"):
fp = None
try:
fp = open(os.path.join("player-skins", image_file), 'rb')
Image.open(fp)
except IOError:
fp.close()
os.remove(os.path.join("player-skins", image_file))
playercache.cleanup()
atexit.register(_cleanup)