Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # import
- from twisted.internet import protocol, reactor
- from twisted.protocols import basic
- from twisted.python import log
- import sys, os, getopt
- import MySQLdb
- # path variables
- libdir = os.path.abspath(os.path.join('lib\\'))
- sys.path.insert(0, libdir)
- # Englorecy Library
- from conf import *
- print "Englorecy Python Server"
- print ""
- # Types
- UP = 0
- ID = 1
- GID = 2
- databaseResults = ""
- dbConfigFileValues = []
- databaseUser = []
- databasePwd = []
- databaseName = []
- databaseHost = []
- databasePort = []
- loginTable = []
- class ServerReceiver(basic.LineReceiver):
- #ServerReceiver handles all request sent to the server
- userName = ""
- userPwd = ""
- userID = 0
- adminLevel = 0
- delimiter = "\0"
- def connectionMade(self):
- # The connectionMade function takes care of what the server should do at a new client connection
- print "DEBUG: Client connected!" # Prints out that a new client is connected
- self.factory.clients.append(self) # Add the new client to the clients list
- # NOTE: The login message is sent at login time, even though the new client is added before that
- # However, since the new client doesn't see the text area on the client until
- # after it is logged in, it won't see the connection message, it will just see the
- # welcome message.
- def connectionLost(self, reason):
- # The connectionLost function takes care of what the server should do at a client drop
- print "DEBUG: Client lost!" # Prints out that a client is disconnected/have been dropped
- self.factory.clients.remove(self) # Remove the client from the client list
- for client in self.factory.clients: # And tell the remaining clients
- client.sendLine("%s disconnected" % self.userName) # That the client disconnected
- UserStorageLayer.userList[self.userID] = []
- def lineReceived(self, line):
- # The lineReceived function is the function that handles everything besides connection/disconnection
- adminCommand = ""
- newline = line.split(":")
- print newline
- if "$$login-request" in line: # If the client sends a login request, then we need to process the information
- print "Login Request Received" # Inform the server manager that a new login request was processed
- # The login request uses the following format:
- # function: login-request <username>,<password>
- self.userName = line.split(' ')[1].split(',')[0] # Get the username
- self.userPwd = line.split(' ')[1].split(',')[1] # Get the password
- DatabaseConnectionLayer().login_check(self.userName, self.userPwd) # Connect to the database and check the inputed username and password,
- # and compare in to the database
- DatabaseConnectionLayer().get_userID(self.userName) # Connect to the database to get the user ID connected to the username
- self.userID = UserStorageLayer.databaseResultsId[0] # and put it in the variable self.userID
- self.adminLevel = UserStorageLayer.userList[self.userID][2]
- print self.adminLevel
- if self.userName in UserStorageLayer.userList[self.userID] and self.userPwd in UserStorageLayer.userList[self.userID] and not UserStorageLayer.userLoggedIn:
- self.sendLine("$$login-answer")
- for client in self.factory.clients:
- client.sendLine("%s connected" % self.userName)
- print "User '%s' logged in" % self.userName
- elif UserStorageLayer.userLoggedIn:
- self.sendLine("$$login-already")
- else:
- self.sendLine("$$login-failed")
- elif "userlist-request" in line: # If the client sends a user-list request, then we need to send the list of clients connected
- for count in UserStorageLayer.userList:
- try:
- info_username = count[0]
- if info_username not in UserStorageLayer.sentList:
- for client in UserStorageLayer.sentList:
- self.sendLine("$$user-list "+client)
- for client in self.factory.clients:
- client.sendLine("$$user-list "+info_username)
- UserStorageLayer.sentList.append(info_username)
- else:
- pass
- except IndexError:
- pass
- elif "$$character-request" in line: # If the client sends a character information request, then we need to process the request.
- # The character request should look something like this:
- # $$character-request: <username>
- self.chrName = UserStorageLayer.userList[self.userID][0]
- self.chrX = UserStorageLayer.userList[self.userID][3]
- self.chrY = UserStorageLayer.userList[self.userID][4]
- self.chrMap = "myMap"
- self.sendLine("$$character-sheet: "+str(self.userID)+" "+self.chrName+" "+str(self.chrX)+" "+str(self.chrY)+" "+self.chrMap)
- for client in self.factory.clients:
- client.sendLine("$$online-character: "+str(self.userID)+" "+self.chrName+" "+str(self.chrX)+" "+str(self.chrY)+" "+self.chrMap)
- elif "$$welcome-request" in line: # The server accepts the sent welcome message request
- self.sendLine("<font color='#0000FF'><b>Welcome to Englorecy Online!\nEnjoy your stay!</b></font>") # And sends the welcome message to the client
- elif "!command" in line:
- adminCommand = line.split(' ')[3]
- if adminCommand == "broadcast":
- if self.adminLevel > 0:
- try:
- messagelist = line.split(' ')[4:]
- except IndexError:
- self.sendLine("The '<b>broadcast</b>' command requires atleast one extra option")
- for i in range(len(messagelist)):
- message = messagelist[i]
- for client in self.factory.clients:
- client.sendLine("!!broadcast " + message)
- else:
- self.sendLine("This command requires admin access. Your access level is %s" % str(self.adminLevel))
- elif adminCommand == "changemap":
- if self.adminLevel > 0:
- try:
- map = line.split(' ')[4]
- except IndexError:
- self.sendLine("The '<b>changemap</b>' command requires atleast one extra option")
- map = ""
- self.sendLine("$$map_change " + map)
- else:
- self.sendLine("This command requires admin access. Your access level is %s" % str(self.adminLevel))
- else:
- self.sendLine("<b>"+adminCommand+"</b> is not a valid command.")
- else: # If none of the above are sent, then we assume that it is a regular chat message
- print line
- for client in self.factory.clients:
- client.sendLine(line)
- class UserStorageLayer:
- userList = []
- userListLength = []
- databaseResultsId = []
- userLoggedIn = False
- sentList = []
- characterInfoList = []
- class DatabaseConnectionLayer:
- print "Parsing database.txt..."
- try:
- ConfigFileOperation().open_file("database.txt")
- dbConfigFileValues = ConfigTempLayer.return_var
- databaseHost = dbConfigFileValues[0]
- databasePort = dbConfigFileValues[1]
- databaseName = dbConfigFileValues[2]
- databaseUser = dbConfigFileValues[3]
- databasePwd = dbConfigFileValues[4]
- loginTable = dbConfigFileValues[5]
- except: print "database.txt Parsing failed!"
- def _connect(self):
- self.databaseConnection = MySQLdb.Connect(host=str(self.databaseHost), port=int(self.databasePort), user="englorecy", passwd="12QWaszx", db=self.databaseName)
- self.databaseCursor = self.databaseConnection.cursor()
- def _disconnect(self):
- self.databaseConnection.close()
- def _action(self, sqlrequest="", type=UP, optparameter=None):
- if type == UP:
- sqlRequest = sqlrequest
- try:
- self.databaseCursor.execute(sqlRequest)
- databaseResults = self.databaseCursor.fetchall()
- except: print "SQL Syntax error detected. Please check your SQL String"
- for res in databaseResults:
- userID = res[0]
- if res[1] not in UserStorageLayer.userList[userID] and res[2] not in UserStorageLayer.userList[userID]:
- UserStorageLayer.userList[userID].append(res[1])
- UserStorageLayer.userList[userID].append(res[2])
- UserStorageLayer.userList[userID].append(res[3])
- UserStorageLayer.userList[userID].append(res[4])
- UserStorageLayer.userList[userID].append(res[5])
- UserStorageLayer.userLoggedIn = False
- else:
- print "User '%s' is already logged in" % res[1]
- UserStorageLayer.userLoggedIn = True
- UserStorageLayer.userList[userID] = []
- print "User '%s' is disconnected" % res[1]
- elif type == ID:
- sqlRequest = ("SELECT id FROM %s" % self.loginTable)
- self.databaseCursor.execute(sqlRequest)
- self.results = self.databaseCursor.fetchall()
- for idl in self.results:
- UserStorageLayer.userListLength.append(idl)
- def login_check(self, username, password):
- self._connect()
- self._action("SELECT id, username, password, admin_level, x, y FROM "+self.loginTable+" WHERE username = '"+username+"' AND password = '"+password+"'")
- self._disconnect()
- def idLength_check(self):
- self._connect()
- self._action("", ID)
- self._disconnect()
- def get_userID(self, username):
- self._connect()
- sqlRequest = ("SELECT id FROM "+self.loginTable+" WHERE username ='"+username+"'")
- self.databaseCursor.execute(sqlRequest)
- res = self.databaseCursor.fetchall()
- UserStorageLayer.databaseResultsId = []
- UserStorageLayer.databaseResultsId.append(res[0][0])
- self._disconnect()
- class XMLSocket(protocol.ServerFactory):
- clients = []
- def __init__(self, protocol=None):
- self.protocol = protocol
- def main(port=717):
- reactor.listenTCP(port, XMLSocket(ServerReceiver))
- print "Listening to port %s..." % port
- print "Opening Database connection"
- DatabaseConnectionLayer()._connect()
- print "Database Connection established"
- print "Setting up User list length"
- DatabaseConnectionLayer().idLength_check()
- UserStorageLayer.userList = [[] for i in range(len(UserStorageLayer.userListLength))]
- print UserStorageLayer.userList
- if len(UserStorageLayer.userList) == len(UserStorageLayer.userListLength):
- print "User list setup successful"
- else: print "User list setup failed"
- print "Starting Reactor"
- reactor.run()
- # DatabaseConnectionLayer()._disconnect()
- print "Shutting down the server..."
- if __name__=='__main__':
- try:
- opts, args = getopt.getopt(sys.argv[1:], "", ["port="])
- try:
- main(int(sys.argv[2]))
- except IndexError:
- main()
- except getopt.GetoptError:
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement