Minor cleanup, pep8 compliance

This commit is contained in:
Ammar Askar 2014-10-08 22:12:37 +05:00
parent 85112fba1d
commit 1982716f73
5 changed files with 78 additions and 71 deletions

View File

@ -1,15 +1,15 @@
import urllib2
import urllib
import json
BASE_URL = 'https://authserver.mojang.com/'
AGENT_INFO = {"name": "Minecraft", "version": 1}
"""Class to hold responses from Yggdrasil
"""
class Response:
class Response(object):
"""Class to hold responses from Yggdrasil
"""
error = False
payload = None
def make_request(url, payload):
@ -50,10 +50,11 @@ def make_request(url, payload):
response.payload = json_response
return response
"""Yet another container class, this time to hold login info since it'll probably
be need to passed around a lot afterwards
"""
class LoginResponse:
class LoginResponse(object):
"""Yet another container class, this time to hold login info since it'll probably
be need to passed around a lot afterwards
"""
pass
@ -64,7 +65,7 @@ def login_to_minecraft(username, password):
If there is an error, it will be accompanied with a `human_error` field.
Otherwise `access_token`, `profile_id` and `username` fields will be present in the response.
"""
payload = { "username": username, "password": password, "agent": AGENT_INFO }
payload = {"username": username, "password": password, "agent": AGENT_INFO}
response = make_request(BASE_URL + "authenticate", payload)
login_response = LoginResponse()

View File

@ -1,13 +1,14 @@
from packets import *
from start import PROTOCOL_VERSION
from collections import deque
from threading import Lock
from types import VarInt
import threading
import socket
import time
import select
from packets import *
from start import PROTOCOL_VERSION
from types import VarInt
class Connection:
"""This class represents a connection to a minecraft
@ -62,7 +63,7 @@ class Connection:
self._handshake()
def _connect(self):
#Connect a socket to the server and create a file object from the socket
# Connect a socket to the server and create a file object from the socket
#The file object is used to read any and all data from the socket since it's "guaranteed"
#to read the number of bytes specified, the socket itself will mostly be
#used to write data upstream to the server
@ -98,7 +99,7 @@ class NetworkingThread(threading.Thread):
num_packets = 0
self.connection.write_lock.acquire()
while self.connection._pop_packet():
self.connection._pop_packet()
num_packets += 1
@ -108,7 +109,7 @@ class NetworkingThread(threading.Thread):
# Read and react to as many as 50 packets
num_packets = 0
packet = self.connection.reactor.read_packet(self.connection.socket, self.connection.file_object)
packet = self.connection.reactor.read_packet(self.connection.file_object)
while packet:
num_packets += 1
@ -116,13 +117,12 @@ class NetworkingThread(threading.Thread):
if num_packets >= 50:
break
packet = self.connection.reactor.read_packet(self.connection.socket, self.connection.file_object)
packet = self.connection.reactor.read_packet(self.connection.file_object)
time.sleep(0.05)
class PacketReactor:
state_name = None
clientbound_packets = None
@ -131,7 +131,7 @@ class PacketReactor:
def __init__(self, connection):
self.connection = connection
def read_packet(self, socket, stream):
def read_packet(self, stream):
ready = select.select([self.connection.socket], [], [], 0.5)
if ready[0]:
length = VarInt.read(stream)
@ -152,17 +152,16 @@ class PacketReactor:
class HandshakeReactor(PacketReactor):
clientbound_packets = state_handshake_clientbound
class StatusReactor(PacketReactor):
clientbound_packets = state_status_clientbound
def react(self, packet):
if packet.name == "response":
if packet.id == ResponsePacket.id:
import json
print json.loads(packet.json_response)
ping_packet = PingPacket()

View File

@ -1,8 +1,9 @@
from types import *
from io import BytesIO
from types import *
class PacketBuffer:
class PacketBuffer(object):
b = BytesIO()
def send(self, value):
@ -11,11 +12,15 @@ class PacketBuffer:
def get_writable(self):
return self.b.getvalue()
class Packet:
class Packet(object):
name = "base"
definition = []
def __init__(self):
pass
def read(self, file_object):
for field in self.definition:
for var_name, data_type in field.iteritems():
@ -32,58 +37,64 @@ class Packet:
data = getattr(self, var_name)
data_type.send(data, packet_buffer)
VarInt.send(len(packet_buffer.get_writable()), socket) # Packet Size
socket.send(packet_buffer.get_writable()) # Packet Payload
VarInt.send(len(packet_buffer.get_writable()), socket) # Packet Size
socket.send(packet_buffer.get_writable()) # Packet Payload
# Handshake State
#==============
# ==============
class HandShakePacket(Packet):
id = 0x00
name = "handshake"
definition = [
{'protocol_version': VarInt},
{'server_address': String},
{'server_port': UnsignedShort},
{'next_state': VarInt}]
{'protocol_version': VarInt},
{'server_address': String},
{'server_port': UnsignedShort},
{'next_state': VarInt}]
state_handshake_clientbound = {
}
state_handshake_serverbound = {
0x00: HandShakePacket
}
# Status State
#==============
class ResponsePacket(Packet):
id = 0x00
name = "response"
definition = [
{'json_response': String}]
{'json_response': String}]
class PingPacket(Packet):
id = 0x01
name = "ping"
definition = [
{'time': Long}]
{'time': Long}]
state_status_clientbound = {
0x00: ResponsePacket,
0x01: PingPacket
}
class RequestPacket(Packet):
id = 0x00
name = "request"
definition = []
class PingPacket(Packet):
id = 0x01
name = "ping"
definition = [
{'time': Long}]
{'time': Long}]
state_status_serverbound = {
0x00: RequestPacket,
@ -93,28 +104,28 @@ state_status_serverbound = {
# Login State
#==============
class DisconnectPacket(Packet):
id = 0x00
name = "disconnect"
definition = [
{'json_data': String}]
class EncryptionRequestPacket(Packet):
{'json_data': String}]
class EncryptionRequestPacket(Packet):
id = 0x01
name = "encryption request"
definition = [
{'server_id': String},
{'public_key': ByteArray},
{'verify_token': ByteArray}]
{'server_id': String},
{'public_key': ByteArray},
{'verify_token': ByteArray}]
class LoginSucessPacket(Packet):
id = 0x02
name = "login success"
definition = [
{'UUID': String},
{'Username': String}]
{'UUID': String},
{'Username': String}]
state_login_clientbound = {
0x00: DisconnectPacket,
@ -122,20 +133,21 @@ state_login_clientbound = {
0x02: LoginSucessPacket
}
class LoginStartPacket(Packet):
id = 0x00
name = "login start"
definition = [
{'name': String}]
{'name': String}]
class EncryptionResponsePacket(Packet):
id = 0x01
name = "encryption response"
definition = [
{'shared_secret': ByteArray},
{'verify_token': ByteArray}]
{'shared_secret': ByteArray},
{'verify_token': ByteArray}]
state_login_serverbound = {
0x00: LoginStartPacket,

View File

@ -4,8 +4,8 @@ These definitions and methods are used by the packet definitions
"""
import struct
class Type:
class Type:
@staticmethod
def read(file_object):
pass
@ -14,11 +14,11 @@ class Type:
def send(value, socket):
pass
#=========================================================
# =========================================================
class Boolean(Type):
@staticmethod
def read(file_object):
return struct.unpack('?', file_object.read(1))[0]
@ -29,7 +29,6 @@ class Boolean(Type):
class Byte(Type):
@staticmethod
def read(file_object):
return struct.unpack('>b', file_object.read(1))[0]
@ -40,7 +39,6 @@ class Byte(Type):
class Short(Type):
@staticmethod
def read(file_object):
return struct.unpack('>h', file_object.read(2))[0]
@ -51,7 +49,6 @@ class Short(Type):
class UnsignedShort(Type):
@staticmethod
def read(file_object):
return struct.unpack('>H', file_object.read(2))[0]
@ -62,7 +59,6 @@ class UnsignedShort(Type):
class Integer(Type):
@staticmethod
def read(file_object):
return struct.unpack('>i', file_object.read(4))[0]
@ -73,7 +69,6 @@ class Integer(Type):
class VarInt(Type):
@staticmethod
def read_socket(s):
d = 0
@ -107,7 +102,6 @@ class VarInt(Type):
class Long(Type):
@staticmethod
def read(file_object):
return struct.unpack('>q', file_object.read(8))[0]
@ -118,7 +112,6 @@ class Long(Type):
class Float(Type):
@staticmethod
def read(file_object):
return struct.unpack('>f', file_object.read(4))[0]
@ -127,8 +120,8 @@ class Float(Type):
def send(svalue, socket):
socket.send(struct.pack('>f', value))
class Double(Type):
class Double(Type):
@staticmethod
def read(file_object):
return struct.unpack('>d', file_object.read(8))[0]
@ -139,7 +132,6 @@ class Double(Type):
class ByteArray(Type):
@staticmethod
def read(file_object, length=None):
if length is None:
@ -153,7 +145,6 @@ class ByteArray(Type):
class String(Type):
@staticmethod
def read(file_object):
length = VarInt.read(file_object)

View File

@ -1,25 +1,27 @@
import getpass
import sys
from optparse import OptionParser
import authentication
PROTOCOL_VERSION = 5
def main():
parser = OptionParser()
parser.add_option("-u", "--username", dest="username", default=None,
help="username to log in with")
help="username to log in with")
parser.add_option("-p", "--password", dest="password", default=None,
help="password to log in with")
help="password to log in with")
parser.add_option("-s", "--server", dest="server", default=None,
help="server to connect to")
help="server to connect to")
(options, args) = parser.parse_args()
if not options.username:
options.username = raw_input("Enter your username: ")
@ -27,8 +29,9 @@ def main():
options.password = getpass.getpass("Enter your password: ")
login_response = authentication.login_to_minecraft(options.username, options.password)
from pprint import pprint # TODO: remove debug
pprint(vars(login_response)) # TODO: remove debug
from pprint import pprint # TODO: remove debug
pprint(vars(login_response)) # TODO: remove debug
if login_response.error:
print login_response.human_error
@ -48,6 +51,7 @@ def main():
port = 25565
from network.connection import Connection
connection = Connection(address, port, login_response)
connection.status()