Skip to content

Instantly share code, notes, and snippets.

@cindyker
Forked from Byteflux/uuidconvert.py
Last active August 29, 2015 13:59
Show Gist options
  • Save cindyker/10585982 to your computer and use it in GitHub Desktop.
Save cindyker/10585982 to your computer and use it in GitHub Desktop.
import sys
import os
import math
import urllib2
import json
import time
import shutil
import uuid
from nbt import nbt # pip install nbt
import time
from functools import wraps
def retry(ExceptionToCheck, tries=4, delay=3, backoff=2, logger=None):
"""Retry calling the decorated function using an exponential backoff.
http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/
original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry
:param ExceptionToCheck: the exception to check. may be a tuple of
exceptions to check
:type ExceptionToCheck: Exception or tuple
:param tries: number of times to try (not retry) before giving up
:type tries: int
:param delay: initial delay between retries in seconds
:type delay: int
:param backoff: backoff multiplier e.g. value of 2 will double the delay
each retry
:type backoff: int
:param logger: logger to use. If None, print
:type logger: logging.Logger instance
"""
def deco_retry(f):
@wraps(f)
def f_retry(*args, **kwargs):
mtries, mdelay = tries, delay
while mtries > 1:
try:
return f(*args, **kwargs)
except ExceptionToCheck, e:
msg = "%s, Retrying in %d seconds..." % (str(e), mdelay)
if logger:
logger.warning(msg)
else:
print msg
time.sleep(mdelay)
mtries -= 1
mdelay *= backoff
return f(*args, **kwargs)
return f_retry # true decorator
return deco_retry
@retry(urllib2.URLError, tries=4, delay=3, backoff=2)
def urlopen_with_retry(urlstring):
return urllib2.urlopen(urlstring)
def convert(path):
if not os.path.isdir(path):
sys.stderr.write('Path is not directory or does not exist:' + path)
return False
max_payload_size = 50
profile_url = 'https://api.mojang.com/profiles/page/1'
player_data_path = os.path.join(path, 'players')
target_data_path = os.path.join(path, 'playerdata')
player_files = []
for player_file in os.listdir(player_data_path):
if os.path.isfile(os.path.join(player_data_path, player_file)) and player_file.endswith('.dat'):
player_files.append(os.path.join(player_data_path, player_file))
if not player_files:
sys.stderr.write('No player data found!\n')
return False
if not os.path.isdir(target_data_path):
os.mkdir(target_data_path)
payload = []
current = 0
for player_file in player_files:
current = current + 1
payload.append({
'name': os.path.splitext(os.path.basename(player_file))[0],
'agent': 'minecraft'
})
if (float(current) % max_payload_size) != 0 and current != len(player_files):
continue
request = urllib2.Request(profile_url, json.dumps(payload), {'Content-Type': 'application/json'})
#response = urllib2.urlopen(request)
#now with retries cause mojang's web api sucks.
try:
response = urlopen_with_retry(request)
except urllib2.HTTPError, e:
sys.stderr.write('HTTPError = ' + str(e.code))
except urllib2.URLError, e:
sys.stderr.write('URLError = ' + str(e.reason))
except httplib.HTTPException, e:
sys.stderr.write('HTTPException')
except Exception:
import traceback
sys.stderr.write('generic exception: ' + traceback.format_exc())
data = json.loads(response.read())
if len(data['profiles']) != len(payload):
payload_names = set([p['name'] for p in payload])
response_names = set([p['name'] for p in data['profiles']])
sys.stderr.write('Missing profiles from API response: ' + repr(list(payload_names - response_names)) + '\n')
payload = []
for profile in data['profiles']:
src = os.path.join(player_data_path, profile['name'] + '.dat')
dst = os.path.join(target_data_path, str(uuid.UUID(profile['id'])) + '.dat')
try:
nbtfile = nbt.NBTFile(src, 'rb')
except IOError as e:
sys.stderr.write('Error reading NBT file: ' + src + ' (' + str(e) + ')\n')
continue
try:
bukkit = nbtfile['bukkit']
except KeyError:
bukkit = nbt.TAG_Compound()
bukkit.name = 'bukkit'
nbtfile.tags.append(bukkit)
try:
lastKnownName = bukkit['lastKnownName']
except KeyError:
lastKnownName = nbt.TAG_String(name='lastKnownName')
bukkit.tags.append(lastKnownName)
lastKnownName.value = profile['name']
nbtfile.write_file(dst)
return True
if __name__ == '__main__':
path = 'world'
if len(sys.argv) > 1:
path = sys.argv[1]
if convert(path):
print 'Player data has been successfully converted.'
@cindyker
Copy link
Author

Quoting Byteflux:
"
If like me your player data is not being converted this script may be of some use to you.

First step: Backup your data. If you have any previously created UUID-based player data files, they might be overwritten during conversion.

Next, install the dependency nbt module as root:

pip install nbt

Finally, run the conversion script:

python uuidconvert.py <worldpath>

Note: Replace with the file system path to your main world

The conversion script may take a long time to run and may also print some errors that most likely are harmless,

After the conversion has completed, you may want to rename the players folder inside your world just for good measure. Call it whatever you want, or delete it if you already have backups elsewhere.

This script was tested in Python 2.7. It might work in older versions, but it will most likely not work in Python 3.
"

Originally forked from : https://gist.github.com/Byteflux/10575939

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment