Advertisement
Guest User

Untitled

a guest
Jun 1st, 2017
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 12.22 KB | None | 0 0
  1. # import
  2. from twisted.internet import protocol, reactor
  3. from twisted.protocols import basic
  4. from twisted.python import log
  5. import sys, os, getopt
  6. import MySQLdb
  7.  
  8. # path variables
  9. libdir = os.path.abspath(os.path.join('lib\\'))
  10. sys.path.insert(0, libdir)
  11.  
  12. # Englorecy Library
  13. from conf import *
  14.  
  15. print "Englorecy Python Server"
  16. print ""
  17.  
  18. # Types
  19. UP = 0
  20. ID = 1
  21. GID = 2
  22. databaseResults = ""
  23.  
  24. dbConfigFileValues = []
  25. databaseUser = []
  26. databasePwd = []
  27. databaseName = []
  28. databaseHost = []
  29. databasePort = []
  30. loginTable = []
  31.  
  32. class ServerReceiver(basic.LineReceiver):
  33.     #ServerReceiver handles all request sent to the server
  34.    
  35.     userName = ""
  36.     userPwd = ""
  37.     userID = 0
  38.     adminLevel = 0
  39.    
  40.     delimiter = "\0"
  41.    
  42.     def connectionMade(self):
  43.     # The connectionMade function takes care of what the server should do at a new client connection
  44.    
  45.         print "DEBUG: Client connected!" # Prints out that a new client is connected
  46.         self.factory.clients.append(self) # Add the new client to the clients list
  47.        
  48.         # NOTE: The login message is sent at login time, even though the new client is added before that
  49.         # However, since the new client doesn't see the text area on the client until
  50.         # after it is logged in, it won't see the connection message, it will just see the
  51.         # welcome message.
  52.        
  53.     def connectionLost(self, reason):
  54.     # The connectionLost function takes care of what the server should do at a client drop
  55.    
  56.         print "DEBUG: Client lost!" # Prints out that a client is disconnected/have been dropped
  57.        
  58.         self.factory.clients.remove(self) # Remove the client from the client list
  59.        
  60.         for client in self.factory.clients: # And tell the remaining clients
  61.             client.sendLine("%s disconnected" % self.userName) # That the client disconnected
  62.        
  63.         UserStorageLayer.userList[self.userID] = []
  64.    
  65.     def lineReceived(self, line):
  66.     # The lineReceived function is the function that handles everything besides connection/disconnection
  67.         adminCommand = ""
  68.         newline = line.split(":")
  69.         print newline
  70.         if "$$login-request" in line: # If the client sends a login request, then we need to process the information
  71.        
  72.             print "Login Request Received" # Inform the server manager that a new login request was processed
  73.             # The login request uses the following format:
  74.             # function: login-request <username>,<password>
  75.            
  76.             self.userName = line.split(' ')[1].split(',')[0] # Get the username
  77.             self.userPwd = line.split(' ')[1].split(',')[1] # Get the password
  78.            
  79.             DatabaseConnectionLayer().login_check(self.userName, self.userPwd) # Connect to the database and check the inputed username and password,
  80.                                                                                 # and compare in to the database
  81.            
  82.             DatabaseConnectionLayer().get_userID(self.userName) # Connect to the database to get the user ID connected to the username
  83.             self.userID = UserStorageLayer.databaseResultsId[0] # and put it in the variable self.userID
  84.            
  85.             self.adminLevel = UserStorageLayer.userList[self.userID][2]
  86.             print self.adminLevel
  87.            
  88.             if self.userName in UserStorageLayer.userList[self.userID] and self.userPwd in UserStorageLayer.userList[self.userID] and not UserStorageLayer.userLoggedIn:
  89.                 self.sendLine("$$login-answer")
  90.                 for client in self.factory.clients:
  91.                     client.sendLine("%s connected" % self.userName)
  92.                 print "User '%s' logged in" % self.userName
  93.                
  94.             elif UserStorageLayer.userLoggedIn:
  95.                 self.sendLine("$$login-already")
  96.                
  97.             else:
  98.                 self.sendLine("$$login-failed")
  99.        
  100.         elif "userlist-request" in line: # If the client sends a user-list request, then we need to send the list of clients connected
  101.            
  102.             for count in UserStorageLayer.userList:
  103.                 try:
  104.                     info_username = count[0]
  105.                    
  106.                     if info_username not in UserStorageLayer.sentList:
  107.                    
  108.                         for client in UserStorageLayer.sentList:
  109.                             self.sendLine("$$user-list "+client)
  110.                        
  111.                         for client in self.factory.clients:
  112.                             client.sendLine("$$user-list "+info_username)
  113.                        
  114.                         UserStorageLayer.sentList.append(info_username)
  115.                    
  116.                     else:
  117.                         pass
  118.                
  119.                 except IndexError:
  120.                     pass
  121.            
  122.         elif "$$character-request" in line:     # If the client sends a character information request, then we need to process the request.
  123.                                                 # The character request should look something like this:
  124.                                                 # $$character-request: <username>
  125.            
  126.             self.chrName = UserStorageLayer.userList[self.userID][0]
  127.             self.chrX = UserStorageLayer.userList[self.userID][3]
  128.             self.chrY = UserStorageLayer.userList[self.userID][4]
  129.             self.chrMap = "myMap"
  130.            
  131.             self.sendLine("$$character-sheet: "+str(self.userID)+" "+self.chrName+" "+str(self.chrX)+" "+str(self.chrY)+" "+self.chrMap)
  132.            
  133.             for client in self.factory.clients:
  134.                 client.sendLine("$$online-character: "+str(self.userID)+" "+self.chrName+" "+str(self.chrX)+" "+str(self.chrY)+" "+self.chrMap)
  135.            
  136.         elif "$$welcome-request" in line: # The server accepts the sent welcome message request
  137.             self.sendLine("<font color='#0000FF'><b>Welcome to Englorecy Online!\nEnjoy your stay!</b></font>") # And sends the welcome message to the client
  138.        
  139.         elif "!command" in line:
  140.        
  141.             adminCommand = line.split(' ')[3]
  142.            
  143.             if adminCommand == "broadcast":
  144.                 if self.adminLevel > 0:
  145.                     try:
  146.                         messagelist = line.split(' ')[4:]
  147.                     except IndexError:
  148.                         self.sendLine("The '<b>broadcast</b>' command requires atleast one extra option")
  149.                
  150.                     for i in range(len(messagelist)):
  151.                         message = messagelist[i]
  152.                         for client in self.factory.clients:
  153.                             client.sendLine("!!broadcast " + message)
  154.                 else:
  155.                     self.sendLine("This command requires admin access. Your access level is %s" % str(self.adminLevel))
  156.                        
  157.             elif adminCommand == "changemap":
  158.                 if self.adminLevel > 0:
  159.                     try:
  160.                         map = line.split(' ')[4]
  161.                     except IndexError:
  162.                         self.sendLine("The '<b>changemap</b>' command requires atleast one extra option")
  163.                         map = ""
  164.                     self.sendLine("$$map_change " + map)
  165.                 else:
  166.                     self.sendLine("This command requires admin access. Your access level is %s" % str(self.adminLevel))
  167.            
  168.             else:
  169.                 self.sendLine("<b>"+adminCommand+"</b> is not a valid command.")
  170.  
  171.         else: # If none of the above are sent, then we assume that it is a regular chat message
  172.             print line
  173.             for client in self.factory.clients:
  174.                 client.sendLine(line)
  175.                
  176. class UserStorageLayer:
  177.     userList = []
  178.     userListLength = []
  179.     databaseResultsId = []
  180.     userLoggedIn = False
  181.     sentList = []
  182.     characterInfoList = []
  183.  
  184. class DatabaseConnectionLayer:
  185.     print "Parsing database.txt..."
  186.     try:
  187.         ConfigFileOperation().open_file("database.txt")
  188.         dbConfigFileValues = ConfigTempLayer.return_var
  189.         databaseHost = dbConfigFileValues[0]
  190.         databasePort = dbConfigFileValues[1]
  191.         databaseName = dbConfigFileValues[2]
  192.         databaseUser = dbConfigFileValues[3]
  193.         databasePwd = dbConfigFileValues[4]
  194.         loginTable = dbConfigFileValues[5]
  195.     except: print "database.txt Parsing failed!"
  196.    
  197.     def _connect(self):
  198.        
  199.         self.databaseConnection = MySQLdb.Connect(host=str(self.databaseHost), port=int(self.databasePort), user="englorecy", passwd="12QWaszx", db=self.databaseName)
  200.         self.databaseCursor = self.databaseConnection.cursor()
  201.    
  202.     def _disconnect(self):
  203.         self.databaseConnection.close()
  204.    
  205.     def _action(self, sqlrequest="", type=UP, optparameter=None):
  206.         if type == UP:
  207.             sqlRequest = sqlrequest
  208.             try:
  209.                 self.databaseCursor.execute(sqlRequest)
  210.                 databaseResults = self.databaseCursor.fetchall()
  211.             except: print "SQL Syntax error detected. Please check your SQL String"
  212.             for res in databaseResults:
  213.                 userID = res[0]
  214.                 if res[1] not in UserStorageLayer.userList[userID] and res[2] not in UserStorageLayer.userList[userID]:
  215.                     UserStorageLayer.userList[userID].append(res[1])
  216.                     UserStorageLayer.userList[userID].append(res[2])
  217.                     UserStorageLayer.userList[userID].append(res[3])
  218.                     UserStorageLayer.userList[userID].append(res[4])
  219.                     UserStorageLayer.userList[userID].append(res[5])
  220.                     UserStorageLayer.userLoggedIn = False
  221.                 else:
  222.                     print "User '%s' is already logged in" % res[1]
  223.                     UserStorageLayer.userLoggedIn = True
  224.                     UserStorageLayer.userList[userID] = []
  225.                     print "User '%s' is disconnected" % res[1]
  226.         elif type == ID:
  227.             sqlRequest = ("SELECT id FROM %s" % self.loginTable)
  228.             self.databaseCursor.execute(sqlRequest)
  229.             self.results = self.databaseCursor.fetchall()
  230.             for idl in self.results:
  231.                 UserStorageLayer.userListLength.append(idl)
  232.                
  233.                
  234.     def login_check(self, username, password):
  235.         self._connect()
  236.         self._action("SELECT id, username, password, admin_level, x, y FROM "+self.loginTable+" WHERE username = '"+username+"' AND password = '"+password+"'")
  237.         self._disconnect()
  238.    
  239.     def idLength_check(self):
  240.         self._connect()
  241.         self._action("", ID)
  242.         self._disconnect()
  243.    
  244.     def get_userID(self, username):
  245.         self._connect()
  246.         sqlRequest = ("SELECT id FROM "+self.loginTable+" WHERE username ='"+username+"'")
  247.         self.databaseCursor.execute(sqlRequest)
  248.         res = self.databaseCursor.fetchall()
  249.         UserStorageLayer.databaseResultsId = []
  250.         UserStorageLayer.databaseResultsId.append(res[0][0])
  251.         self._disconnect()
  252.  
  253. class XMLSocket(protocol.ServerFactory):
  254.     clients = []
  255.  
  256.     def __init__(self, protocol=None):
  257.         self.protocol = protocol
  258.  
  259. def main(port=717):
  260.     reactor.listenTCP(port, XMLSocket(ServerReceiver))
  261.     print "Listening to port %s..." % port
  262.     print "Opening Database connection"
  263.     DatabaseConnectionLayer()._connect()
  264.     print "Database Connection established"
  265.     print "Setting up User list length"
  266.     DatabaseConnectionLayer().idLength_check()
  267.     UserStorageLayer.userList = [[] for i in range(len(UserStorageLayer.userListLength))]
  268.     print UserStorageLayer.userList
  269.     if len(UserStorageLayer.userList) == len(UserStorageLayer.userListLength):
  270.         print "User list setup successful"
  271.     else: print "User list setup failed"
  272.     print "Starting Reactor"
  273.     reactor.run()
  274.    
  275. #    DatabaseConnectionLayer()._disconnect()
  276.     print "Shutting down the server..."
  277.  
  278. if __name__=='__main__':
  279.     try:
  280.         opts, args = getopt.getopt(sys.argv[1:], "", ["port="])
  281.         try:
  282.             main(int(sys.argv[2]))
  283.         except IndexError:
  284.             main()
  285.     except getopt.GetoptError:
  286.         main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement