Advertisement
Guest User

Minecraft clientti

a guest
Jun 21st, 2017
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 14.20 KB | None | 0 0
  1. package me.tr.minechatpc;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.InputStreamReader;
  5. import java.io.OutputStream;
  6. import java.net.Proxy;
  7. import java.net.URL;
  8. import java.util.ArrayList;
  9. import java.util.Arrays;
  10. import java.util.UUID;
  11. import java.util.regex.Matcher;
  12. import java.util.regex.Pattern;
  13.  
  14. import javax.net.ssl.HttpsURLConnection;
  15.  
  16. import org.spacehq.mc.auth.data.GameProfile;
  17. import org.spacehq.mc.auth.exception.request.RequestException;
  18. import org.spacehq.mc.protocol.MinecraftConstants;
  19. import org.spacehq.mc.protocol.MinecraftProtocol;
  20. import org.spacehq.mc.protocol.data.SubProtocol;
  21. import org.spacehq.mc.protocol.data.message.Message;
  22. import org.spacehq.mc.protocol.data.message.TranslationMessage;
  23. import org.spacehq.mc.protocol.data.status.ServerStatusInfo;
  24. import org.spacehq.mc.protocol.data.status.handler.ServerInfoHandler;
  25. import org.spacehq.mc.protocol.data.status.handler.ServerPingTimeHandler;
  26. import org.spacehq.mc.protocol.packet.ingame.client.ClientChatPacket;
  27. import org.spacehq.mc.protocol.packet.ingame.server.ServerChatPacket;
  28. import org.spacehq.mc.protocol.packet.ingame.server.ServerDisconnectPacket;
  29. import org.spacehq.mc.protocol.packet.ingame.server.ServerJoinGamePacket;
  30. import org.spacehq.packetlib.Client;
  31. import org.spacehq.packetlib.Session;
  32. import org.spacehq.packetlib.event.session.DisconnectedEvent;
  33. import org.spacehq.packetlib.event.session.PacketReceivedEvent;
  34. import org.spacehq.packetlib.event.session.SessionAdapter;
  35. import org.spacehq.packetlib.tcp.TcpSessionFactory;
  36.  
  37. import javafx.application.Application;
  38. import javafx.geometry.HPos;
  39. import javafx.geometry.Insets;
  40. import javafx.geometry.Pos;
  41. import javafx.scene.Scene;
  42. import javafx.scene.control.Button;
  43. import javafx.scene.control.Label;
  44. import javafx.scene.control.PasswordField;
  45. import javafx.scene.control.TextArea;
  46. import javafx.scene.control.TextField;
  47. import javafx.scene.layout.GridPane;
  48. import javafx.stage.Stage;
  49.  
  50. public class MinecraftProtocolTest extends Application{
  51.    
  52.     private static final boolean VERIFY_USERS = true;
  53.     private static String HOST = "localhost";
  54.     private static int PORT = 25565;
  55.     private static final Proxy PROXY = Proxy.NO_PROXY;
  56.     private static final Proxy AUTH_PROXY = Proxy.NO_PROXY;
  57.     private static String USERNAME;
  58.     private static String PASSWORD;
  59.     private static TextArea chat;
  60.     private static Client client;
  61.    
  62.     public static void main(String[] args) {
  63.         launch(args);
  64.     }
  65.  
  66.     @Override
  67.     public void start(Stage myStage) throws Exception {
  68.         myStage.setTitle("Minecraft chat/command client");
  69.  
  70.         GridPane rootNode = new GridPane();
  71.         rootNode.setPadding(new Insets(15));
  72.         rootNode.setHgap(5);
  73.         rootNode.setVgap(5);
  74.         rootNode.setAlignment(Pos.TOP_CENTER);
  75.  
  76.         Scene myScene = new Scene(rootNode, 1280, 720);
  77.        
  78.         rootNode.add(new Label("USERNAME/E-MAIL: "), 0, 0);
  79.         TextField username = new TextField();
  80.         rootNode.add(username, 1, 0);
  81.         rootNode.add(new Label("PASSWORD: "), 0, 1);
  82.         PasswordField password = new PasswordField();
  83.         rootNode.add(password, 1, 1);
  84.  
  85.         Button aButton = new Button("Login");
  86.         rootNode.add(aButton, 1, 2);
  87.        
  88.         rootNode.add(new Label("IP: "), 0, 4);
  89.         TextField address = new TextField();
  90.         rootNode.add(address, 1, 4);
  91.         rootNode.add(new Label("PORT: "), 0, 5);
  92.         TextField port = new TextField();
  93.         rootNode.add(port, 1, 5);
  94.  
  95.         Button connectButton = new Button("Connect");
  96.         rootNode.add(connectButton, 1, 6);
  97.        
  98.         rootNode.add(new Label("MESSAGE: "), 0, 8);
  99.         TextField msg = new TextField();
  100.         rootNode.add(msg, 1, 8);
  101.        
  102.         Button sendButton = new Button("Send");
  103.         rootNode.add(sendButton, 2, 8);
  104.        
  105.         Button clearButton = new Button("Clear");
  106.         rootNode.add(clearButton, 1, 11);
  107.        
  108.         Button disconnectButton = new Button("Disconnect");
  109.         rootNode.add(disconnectButton, 1, 12);
  110.        
  111.         rootNode.add(new Label("This software is made by Niklas Haiminen."), 1, 50);
  112.        
  113.         GridPane.setHalignment(aButton, HPos.LEFT);
  114.         chat = new TextArea();
  115.         chat.setEditable(false);
  116.         rootNode.add(new Label("Chat: "), 0, 10);
  117.         rootNode.add(chat, 1, 10);
  118.  
  119.         aButton.setOnAction(e -> {
  120.  
  121.             if(username.getText().length() <= 0 || password.getText().length() <= 0){
  122.                 sendMessage("Please setup the right credentials!");
  123.                 return;
  124.             }
  125.            
  126.             USERNAME = username.getText();
  127.             PASSWORD = password.getText();
  128.             sendMessage("Logged in");
  129.             sendMessage("USERNAME: " + USERNAME + ", PASSWORD: " + PASSWORD);
  130.         });
  131.        
  132.        
  133.        
  134.         sendButton.setOnAction(e -> {
  135.            
  136.             if(username.getText().length() <= 0 || password.getText().length() <= 0){
  137.                 sendMessage("Login before doing anything!");
  138.                 return;
  139.             }
  140.             else{
  141.                 if(msg.getText().length() > 0){
  142.                     client.getSession().send(new ClientChatPacket(msg.getText()));
  143.                     msg.setText("");
  144.                 }
  145.                 else{
  146.                     sendMessage("Can't send empty messages!");
  147.                 }
  148.             }
  149.         });
  150.        
  151.         clearButton.setOnAction(e -> {
  152.             username.setText("");
  153.             password.setText("");
  154.             chat.setText("");
  155.             address.setText("");
  156.             port.setText("");
  157.         });
  158.  
  159.         connectButton.setOnAction(e -> {
  160.            
  161.             if(username.getText().length() <= 0 || password.getText().length() <= 0){
  162.                 sendMessage("Login before doing anything!");
  163.                 return;
  164.             }
  165.             else{
  166.                 USERNAME = username.getText();
  167.                 PASSWORD = password.getText();
  168.                 sendMessage("Logged in");
  169.             }
  170.            
  171.             if(address.getText().length() <= 0 || port.getText().length() <= 0){
  172.                 sendMessage("Please setup the right address and the port!");
  173.                 return;
  174.             }
  175.            
  176.             sendMessage("Connecting...");
  177.            
  178.             HOST = address.getText();
  179.            
  180.             try{
  181.                 PORT = Integer.parseInt(port.getText());
  182.             } catch(NumberFormatException ex){
  183.                 sendMessage("Please use only numbers when typing server port!");
  184.                 return;
  185.             }
  186.            
  187.             try{
  188.                
  189.                 chat.setText("");
  190.                
  191.                 login();
  192.                 status();
  193.                
  194.             } catch (Exception e1) {
  195.                 e1.printStackTrace();
  196.             }
  197.         });
  198.        
  199.         disconnectButton.setOnAction(e -> {
  200.            
  201.             if(username.getText().length() <= 0 || password.getText().length() <= 0){
  202.                 sendMessage("Login before doing anything!");
  203.                 return;
  204.             }
  205.            
  206.             client.getSession().send(new ServerDisconnectPacket("Bye bye!"));
  207.            
  208.         });
  209.        
  210.         myStage.setScene(myScene);
  211.  
  212.         myStage.show();
  213.        
  214.     }
  215.    
  216.     private static void status() {
  217.         MinecraftProtocol protocol = new MinecraftProtocol(SubProtocol.STATUS);
  218.         Client client = new Client(HOST, PORT, protocol, new TcpSessionFactory(PROXY));
  219.         client.getSession().setFlag(MinecraftConstants.AUTH_PROXY_KEY, AUTH_PROXY);
  220.         client.getSession().setFlag(MinecraftConstants.SERVER_INFO_HANDLER_KEY, new ServerInfoHandler() {
  221.             @Override
  222.             public void handle(Session session, ServerStatusInfo info) {
  223.                 sendMessage("------------ Server Info ------------");
  224.                 sendMessage("IP: " + session.getHost() + ":" + session.getPort());
  225.                 sendMessage("Version: " + info.getVersionInfo().getVersionName() + ", " + info.getVersionInfo().getProtocolVersion());
  226.                 sendMessage("MOTD: " + info.getDescription().getFullText());
  227.                 //System.out.println("Icon: " + info.getIcon());
  228.                 sendMessage("Player Count: " + info.getPlayerInfo().getOnlinePlayers() + " / " + info.getPlayerInfo().getMaxPlayers());
  229.                
  230.  
  231.                 // Player list...
  232.                
  233.                 ArrayList<GameProfile> topTen = new ArrayList<>();
  234.                
  235.                 if(info.getPlayerInfo().getPlayers().length <= 10){
  236.                     sendMessage("Players: ");
  237.                     for(GameProfile g : info.getPlayerInfo().getPlayers()){
  238.                         topTen.add(g);
  239.                         sendMessage("- " + g.getName());
  240.                     }
  241.                 }
  242.                 else{
  243.                     sendMessage("Players: (TOP 10)");
  244.                     for(int i = 0; i <= 9; i++){
  245.                         GameProfile g = info.getPlayerInfo().getPlayers()[i];
  246.                         topTen.add(g);
  247.                         sendMessage("- " + g.getName());
  248.                     }
  249.                     sendMessage("And " + (info.getPlayerInfo().getOnlinePlayers() - topTen.size()) + " more players!");
  250.                 }
  251.                 sendMessage("-------------------------------------");
  252.             }
  253.         });
  254.  
  255.         client.getSession().setFlag(MinecraftConstants.SERVER_PING_TIME_HANDLER_KEY, new ServerPingTimeHandler() {
  256.             @Override
  257.             public void handle(Session session, long pingTime) {
  258.                 sendMessage("Server ping took " + pingTime + "ms");
  259.             }
  260.         });
  261.  
  262.         client.getSession().connect();
  263.         while(client.getSession().isConnected()) {
  264.             try {
  265.                 Thread.sleep(5);
  266.             } catch(InterruptedException e) {
  267.                 e.printStackTrace();
  268.             }
  269.         }
  270.     }
  271.  
  272.     private static void login() {
  273.        
  274.         MinecraftProtocol protocol = null;
  275.         System.out.println("USERNAME: " + USERNAME + ", PASSWORD: " + PASSWORD);
  276.         if(VERIFY_USERS) {
  277.             try {
  278.                 protocol = new MinecraftProtocol(USERNAME, PASSWORD, false);
  279.                 sendMessage("Successfully authenticated user.");
  280.             } catch(RequestException e) {
  281.                 e.printStackTrace();
  282.                 return;
  283.             }
  284.         } else {
  285.             protocol = new MinecraftProtocol(USERNAME);
  286.             sendMessage("Didn't authenticate the user.");
  287.         }
  288.  
  289.        
  290.        
  291.         client = new Client(HOST, PORT, protocol, new TcpSessionFactory(PROXY));
  292.         client.getSession().setFlag(MinecraftConstants.AUTH_PROXY_KEY, AUTH_PROXY);
  293.         client.getSession().addListener(new SessionAdapter() {
  294.             @Override
  295.             public void packetReceived(PacketReceivedEvent event) {
  296.                 if(event.getPacket() instanceof ServerJoinGamePacket) {
  297.                     event.getSession().send(new ClientChatPacket("TeamRaiderz häckäilee sen custom Minecraft clientillä!"));
  298.                 } else if(event.getPacket() instanceof ServerChatPacket) {
  299.                     Message message = event.<ServerChatPacket>getPacket().getMessage();
  300.                     sendMessage(message.getFullText());
  301.                     if(message instanceof TranslationMessage) {
  302.                         sendMessage("Received Translation Components: " + Arrays.toString(((TranslationMessage) message).getTranslationParams()));
  303.                     }
  304.  
  305.                    
  306.                 }
  307.             }
  308.  
  309.             @Override
  310.             public void disconnected(DisconnectedEvent event) {
  311.                 sendMessage("Disconnected: " + Message.fromString(event.getReason()).getFullText());
  312.                 if(event.getCause() != null) {
  313.                     event.getCause().printStackTrace();
  314.                 }
  315.             }
  316.            
  317.         });
  318.  
  319.         client.getSession().connect();
  320.     }
  321.    
  322.     private static void sendMessage(String text){
  323.         chat.appendText("\n" + text);
  324.     }
  325.    
  326.     private final static String authserver = "https://authserver.mojang.com";
  327.  
  328.     public static String authenticate(String username, String password) throws Exception {
  329.  
  330.             String genClientToken = UUID.randomUUID().toString();
  331.  
  332.             // Setting up json POST request
  333.             String payload = "{\"agent\": {\"name\": \"Minecraft\",\"version\": 1},\"username\": \"" + username
  334.                     + "\",\"password\": \"" + password + "\",\"clientToken\": \"" + genClientToken + "\"}";
  335.  
  336.             String output = postReadURL(payload, new URL(authserver + "/authenticate"));
  337.  
  338.             // Setting up patterns
  339.             String authBeg = "{\"accessToken\":\"";
  340.             String authEnd = "\",\"clientToken\":\"";
  341.             String clientEnd = "\",\"selectedProfile\"";
  342.  
  343.             // What we are looking for
  344.             String authtoken = getStringBetween(output, authBeg, authEnd);
  345.             return authtoken;
  346.         }
  347.  
  348.     private static String postReadURL(String payload, URL url) throws Exception {
  349.             HttpsURLConnection con = (HttpsURLConnection) (url.openConnection());
  350.  
  351.             con.setReadTimeout(15000);
  352.             con.setConnectTimeout(15000);
  353.             con.setRequestMethod("POST");
  354.             con.setRequestProperty("Content-Type", "application/json");
  355.             con.setDoInput(true);
  356.             con.setDoOutput(true);
  357.  
  358.             OutputStream out = con.getOutputStream();
  359.             out.write(payload.getBytes("UTF-8"));
  360.             out.close();
  361.  
  362.             BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
  363.  
  364.             String output = "";
  365.             String line = null;
  366.             while ((line = in.readLine()) != null)
  367.                 output += line;
  368.  
  369.             in.close();
  370.  
  371.             return output;
  372.         }
  373.  
  374.         private static String getStringBetween(String base, String begin, String end) {
  375.  
  376.             Pattern patbeg = Pattern.compile(Pattern.quote(begin));
  377.             Pattern patend = Pattern.compile(Pattern.quote(end));
  378.  
  379.             int resbeg = 0;
  380.             int resend = base.length() - 1;
  381.  
  382.             Matcher matbeg = patbeg.matcher(base);
  383.  
  384.             if (matbeg.find())
  385.                 resbeg = matbeg.end();
  386.  
  387.             Matcher matend = patend.matcher(base);
  388.  
  389.             if (matend.find())
  390.                 resend = matend.start();
  391.  
  392.             return base.substring(resbeg, resend);
  393.         }
  394. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement