Jump to content

[1.7.10] Converting UUID to username


Romejanic

Recommended Posts

Hello, I'm making a messenger mod for the client. The person sending/receiving the message are identified by their Mojang UUID. However, I need to find a way to convert the UUID to the person's username to be shown on the GUI. This is client-side, so I'd like to do it without the MinecraftSessionService in the MinecraftServer. I've tried making a query to https://sessionserver.mojang.com/session/minecraft/profile/ and converting it to a GameProfile using Gson. Doesn't work. I've tried using a HttpProfileRepository to get it. It takes to long to respond, usually fails, and is for converting the username to a UUID. It is really important that I do this. It would be easier to use usernames as IDs, but I'd like to be ready for the name changes :P

 

Here's my user class:

package assets.mcmessenger.client.messenger;

import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.UUID;

import javax.imageio.ImageIO;

import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.DynamicTexture;
import net.minecraft.util.ResourceLocation;
import assets.mcmessenger.client.messenger.util.GameProfileCreator;

import com.mojang.authlib.GameProfile;

public class User {

private static final String faceFetchUrl = "http://cravatar.eu/helmavatar/%s";

private String uuid;
private String name;

private ResourceLocation face;

public User(String uuid) {

	this.uuid = uuid;

	if(this.uuid.equals(Minecraft.getMinecraft().getSession().getUsername())) {

		this.setName(Minecraft.getMinecraft().getSession().getUsername());

	} else {

		try {

			GameProfile profile = GameProfileCreator.createGameProfileFromUUID(uuid);
			setName(profile.getName());

		} catch(Exception e) {

			setName(e.toString());

		}

	}

}

public String getName() {

	return this.name;

}

public void setName(String name) {

	this.name = name;

}

public UUID getUUID() {

	return UUID.fromString(uuid);

}

public ResourceLocation getFace() {

	if(this.face == null) {

		BufferedImage image = null;

		try {

			image = ImageIO.read(new URL(String.format(faceFetchUrl, getName())));

		} catch(Exception e) {

			e.printStackTrace();

		}

		DynamicTexture texture = new DynamicTexture(0, 0);

		if(image != null) {

			texture = new DynamicTexture(image);

		}

		this.face = Minecraft.getMinecraft().getTextureManager().getDynamicTextureLocation("face_" + getName(), texture);

	}

	return this.face;

}

public boolean equals(User user) {

	return user.uuid == this.uuid;

}

}

 

Here's my profile creator:

package assets.mcmessenger.client.messenger.util;

import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.util.UUID;

import org.apache.commons.io.IOUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonReader;
import com.mojang.api.profiles.Profile;
import com.mojang.authlib.GameProfile;

public class GameProfileCreator {

private static final String fetchIdUrl = "https://api.mojang.com/users/profiles/minecraft/%s?at=%s";
private static final String fetchNameUrl = "https://sessionserver.mojang.com/session/minecraft/profile/%s";

public static Profile createGameProfileFromUsername(String username) {

	try {

		Gson gson = new GsonBuilder().setPrettyPrinting().create();
		String url = String.format(fetchIdUrl, username, String.valueOf(System.currentTimeMillis()));
		JsonReader reader = new JsonReader(new InputStreamReader(new URL(url).openStream()));
		reader.setLenient(true);

		return (Profile)gson.fromJson(reader, Profile.class);

	} catch(Exception e) {

		e.printStackTrace();

	}

	Profile profile = new Profile();
	profile.setName(username);
	return profile;

}

public static Profile createGameProfileFromUUID(String uuid) {

	try {

		Gson gson = new GsonBuilder().setPrettyPrinting().create();
		String url = String.format(fetchNameUrl, uuid);
		JsonReader reader = new JsonReader(new InputStreamReader(new URL(url).openStream()));
		reader.setLenient(true);

		return (Profile)gson.fromJson(reader, Profile.class);

	} catch(Exception e) {

		e.printStackTrace();

	}

	Profile profile = new Profile();
	profile.setId(uuid);
	return profile;

}

}

 

If anyone can help, I would be SO grateful! Thank you very much for your time.

- Romejanic

Romejanic

 

Creator of Witch Hats, Explosive Chickens and Battlefield!

Link to comment
Share on other sites

bigteddy98's uuidlib worked pretty well. I used it for a one time, out of game conversion from UUID to name, dunno how fast it would be

it seems to have mostly disappeared, but went like this

 

given uuid as a string, after

 

uuid = uuid.replaceAll("-", ""); // no dashes

 

it went through

	String name = null;
	try {
		URL url = new URL("https://sessionserver.mojang.com/session/minecraft/profile/" + uuid);
		URLConnection connection = url.openConnection();
		Scanner jsonScanner = new Scanner(connection.getInputStream(), "UTF-8");
		String json = jsonScanner.next();
		JSONParser parser = new JSONParser();
		Object obj = parser.parse(json);
		name = (String) ((JSONObject) obj).get("name");
		jsonScanner.close();
	} catch (Exception ex) {
		ex.printStackTrace();
	}

 

there's probably some reason this is horrible code or unworkable or something, but it did what I wanted to for converting a bunch of UUIDs to usernames

Link to comment
Share on other sites

bigteddy98's uuidlib worked pretty well. I used it for a one time, out of game conversion from UUID to name, dunno how fast it would be

it seems to have mostly disappeared, but went like this

 

given uuid as a string, after

 

uuid = uuid.replaceAll("-", ""); // no dashes

 

it went through

	String name = null;
	try {
		URL url = new URL("https://sessionserver.mojang.com/session/minecraft/profile/" + uuid);
		URLConnection connection = url.openConnection();
		Scanner jsonScanner = new Scanner(connection.getInputStream(), "UTF-8");
		String json = jsonScanner.next();
		JSONParser parser = new JSONParser();
		Object obj = parser.parse(json);
		name = (String) ((JSONObject) obj).get("name");
		jsonScanner.close();
	} catch (Exception ex) {
		ex.printStackTrace();
	}

 

there's probably some reason this is horrible code or unworkable or something, but it did what I wanted to for converting a bunch of UUIDs to usernames

 

Thanks for your response. The initial method didn't work, so I had to change it to this:

 

public static String getName(String uuid) {

	String name = null;

	try {

		URL url = new URL("https://sessionserver.mojang.com/session/minecraft/profile/" + uuid);
		BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
		StringBuilder sb = new StringBuilder();
		String line;

		while((line = reader.readLine()) != null) {

			sb.append(line + "\n");

		}

		System.out.println(sb.toString());

		JsonParser parser = new JsonParser();
		JsonElement obj = parser.parse(sb.toString().trim());
		name = obj.getAsJsonObject().get("name").getAsString();
		reader.close();

	} catch (Exception ex) {

		ex.printStackTrace();
		name = ex.toString();

	}

	return name;

}

 

It was saying that I couldn't convert the response to a Json object. I put the print in and the string returning from the server was empty. I pasted the URL in Chrome along with a UUID at the end, and nothing happened. The script doesn't return anything. I just need another source to get the json code :(

 

 

Romejanic

 

Creator of Witch Hats, Explosive Chickens and Battlefield!

Link to comment
Share on other sites

Actually, I misread.  UUID to username, not other way around.

So, use MinecraftServer.getServer().func_152652_a(<uuid>).

If that returns null, use this to request it from the servers.

 

Yeah, but my mod is client-side. I can't use the server. I guess I could make my own instance of the cache, but that might be a little dangerous. I'll try it anyway.

Romejanic

 

Creator of Witch Hats, Explosive Chickens and Battlefield!

Link to comment
Share on other sites

Uhm... why do you need that clientside?! That sounds unusual.

 

I'm making a messaging service, and the message identification is based on UUIDs to support name changes. It has zero involvement with the server, it's all on the client.

Romejanic

 

Creator of Witch Hats, Explosive Chickens and Battlefield!

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • Slot deposit 3000 adalah situs slot deposit 3000 via dana yang super gacor dimana para pemain dijamin garansi wd hari ini juga hanya dengan modal receh berupa deposit sebesar 3000 baik via dana, ovo, gopay maupun linkaja untuk para pemain pengguna e-wallet di seluruh Indonesia.   DAFTAR & LOGIN AKUN PRO SLOT DEPOSIT 3000 ⭐⭐⭐ KLIK DISINI ⭐⭐⭐  
    • OLXTOTO: Menikmati Sensasi Bermain Togel dan Slot dengan Aman dan Mengasyikkan Dunia perjudian daring terus berkembang dengan cepat, dan salah satu situs yang telah menonjol dalam pasar adalah OLXTOTO. Sebagai platform resmi untuk permainan togel dan slot, OLXTOTO telah memenangkan kepercayaan banyak pemain dengan menyediakan pengalaman bermain yang aman, adil, dan mengasyikkan. DAFTAR OLXTOTO DISINI <a href="https://imgbb.com/"><img src="https://i.ibb.co/GnjSVpx/daftar1-480x480.webp" alt="daftar1-480x480" border="0" /></a> Keamanan Sebagai Prioritas Utama Salah satu aspek utama yang membuat OLXTOTO begitu menonjol adalah komitmennya terhadap keamanan pemain. Dengan menggunakan teknologi enkripsi terkini, situs ini memastikan bahwa semua informasi pribadi dan keuangan para pemain tetap aman dan terlindungi dari akses yang tidak sah. Beragam Permainan yang Menarik Di OLXTOTO, pemain dapat menemukan beragam permainan yang menarik untuk dinikmati. Mulai dari permainan klasik seperti togel hingga slot modern dengan fitur-fitur inovatif, ada sesuatu untuk setiap selera dan preferensi. Grafik yang memukau dan efek suara yang mengagumkan menambah keseruan setiap putaran. Peluang Menang yang Tinggi Salah satu hal yang paling menarik bagi para pemain adalah peluang menang yang tinggi yang ditawarkan oleh OLXTOTO. Dengan pembayaran yang adil dan peluang yang setara bagi semua pemain, setiap taruhan memberikan kesempatan nyata untuk memenangkan hadiah besar. Layanan Pelanggan yang Responsif Tim layanan pelanggan OLXTOTO siap membantu para pemain dengan setiap pertanyaan atau masalah yang mereka hadapi. Dengan layanan yang ramah dan responsif, pemain dapat yakin bahwa mereka akan mendapatkan bantuan yang mereka butuhkan dengan cepat dan efisien. Kesimpulan OLXTOTO telah membuktikan dirinya sebagai salah satu situs terbaik untuk penggemar togel dan slot online. Dengan fokus pada keamanan, beragam permainan yang menarik, peluang menang yang tinggi, dan layanan pelanggan yang luar biasa, tidak mengherankan bahwa situs ini telah menjadi pilihan utama bagi banyak pemain. Jadi, jika Anda mencari pengalaman bermain yang aman, adil, dan mengasyikkan, jangan ragu untuk bergabung dengan OLXTOTO hari ini dan rasakan sensasi kemenangan!
    • Slot deposit dana adalah situs slot deposit dana yang juga menerima dari e-wallet lain seperti deposit via dana, ovo, gopay & linkaja terlengkap saat ini, sehingga para pemain yang tidak memiliki rekening bank lokal bisa tetap bermain slot dan terbantu dengan adanya fitur tersebut.   DAFTAR & LOGIN AKUN PRO SLOT DEPOSIT DANA ⭐⭐⭐ KLIK DISINI ⭐⭐⭐  
    • Slot deposit dana adalah situs slot deposit dana minimal 5000 yang dijamin garansi super gacor dan gampang menang, dimana para pemain yang tidak memiliki rekening bank lokal tetap dalam bermain slot dengan melakukan deposit dana serta e-wallet lainnya seperti ovo, gopay maupun linkaja lengkap. Agar para pecinta slot di seluruh Indonesia tetap dapat menikmati permainan tanpa halangan apapun khususnya metode deposit, dimana ketersediaan cara deposit saat ini yang lebih beragam tentunya sangat membantu para pecinta slot.   DAFTAR & LOGIN AKUN PRO SLOT DEPOSIT DANA ⭐⭐⭐ KLIK DISINI ⭐⭐⭐  
    • Slot deposit pulsa adalah situs slot deposit pulsa tanpa potongan apapun yang dijamin garansi terpercaya, dimana kamu bisa bermain slot dengan melakukan deposit pulsa dan tanpa dikenakan potongan apapun sehingga dana yang masuk ke dalam akun akan 100% utuh. Proses penarikan dana juga dijamin gampang dan tidak sulit sehingga kamu tidak perlu khawatir akan kemenangan yang akan kamu peroleh dengan sangat mudah jika bermain disini.   DAFTAR & LOGIN AKUN PRO SLOT DEPOSIT PULSA TANPA POTONGAN ⭐⭐⭐ KLIK DISINI ⭐⭐⭐  
  • Topics

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.