def itemChange(self, item): value = item.text() if str(value).isdigit(): if len(value) < 2: value = "0" + value item.setText(value) row = item.row() count = 0 for card in self.cardList: if count == row: FileHelper().deleteCard(card) newCard = Card(card.name,card.card,card.rank,card.cardType,card.attribute,card.speedDuel,card.atkPoints,card.defPoints,value) FileHelper().saveCard(newCard) count = count + 1 elif len(value) == 2: item.setText(value) row = item.row() count = 0 for card in self.cardList: if count == row: FileHelper().deleteCard(card) newCard = Card(card.name,card.card,card.rank,card.cardType,card.attribute,card.speedDuel,card.atkPoints,card.defPoints,value) FileHelper().saveCard(newCard) count = count + 1 else: QMessageBox.about(self.tableWidget,"Error", "Anzahl darf nur Zahlen enthalten. Wert wurde nicht gespeicher.")
def importScripts(self): self.decEncHelper = DecodingEncodingHelper() self.channelManager = ChannelManager() self.clientManager = ClientManager() self.inputHandler = InputHandler(self.upTime) self.fileHelper = FileHelper() self.logHelper = LogHelper()
def importScripts(self): self.decEncHelper = DecodingEncodingHelper() self.channelManager = ChannelManager() self.clientManager = ClientManager() self.fileHelper = FileHelper() self.logHelper = LogHelper() self.mysqlHelper = MysqlHelper()
def __init__(self): self.fileHelper = FileHelper() self.logHelper = LogHelper() config = self.fileHelper.getConfig("Mysql Server Config") try: self.connection = mysql.connector.connect(user=config.username, password=config.password, host=config.ip, database=config.database) except: print("Couldn't establish connection to mysql database(" + config.database + ") with ip: " + config.ip) #TODO: find a way to handle with this
def createTableViewButton(self): tableViewThread = threading.Thread( target=TableViewWindow().createTableViewWindow( FileHelper().loadCards(), self.dontShowCardsWithQuantityZero.get())) tableViewThread.daemon = True tableViewThread.start()
def createSearchWindowButton(self): searchEditThread = threading.Thread( target=SearchWindow().createSearchWindow( FileHelper().loadCards(), self.dontShowCardsWithQuantityZero.get())) searchEditThread.daemon = True searchEditThread.start()
def deleteRow(self): for row in self.tableWidget.selectedIndexes(): rowCount = row.row() count = 0 for card in self.cardList: if count == rowCount: FileHelper().deleteCard(card) count = count + 1 messagebox.showinfo("Info", "Zum Hauptmenu zurückkehren um aktualisierte tabelle zu erhalten.")
def __init__(self, announce): self.mysqlMode = 0 # 0 = Mysql; 1 = MysqlLite self.fileHelper = FileHelper() self.logHelper = LogHelper() config = self.fileHelper.getConfig("Mysql Server Config") try: self.connection = mysql.connector.connect(user=config.username, password=config.password, host=config.ip, database=config.database) except: self.mysqlMode = 1 if (announce): print( "[" + datetime.datetime.now().strftime("%H:%M:%S") + " ERROR]: Couldn't establish connection to mysql database(" + config.database + ") with ip: " + config.ip) print("[" + datetime.datetime.now().strftime("%H:%M:%S") + " INFO]: Falling back to MysqlLite.") #sqllite self.conn = self.create_connection("data/database.db") checkForAccountsTable = "SELECT * FROM accounts" result = self.executeCommandOnLite(self.conn, checkForAccountsTable) try: for row in result: if row[0] == 1: result = True else: result = False except: result = False if result == False: createTableStatement = "CREATE TABLE accounts (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL, password TEXT NOT NULL, email TEXT NOT NULL, rank TEXT NOT NULL, loggedIn TINYINT NOT NULL DEFAULT '0');" print("[" + datetime.datetime.now().strftime("%H:%M:%S") + " INFO]: Created accounts table in MysqlLite database.") self.executeCommandOnLite(self.conn, createTableStatement)
class Client: def importScripts(self): self.decEncHelper = DecodingEncodingHelper() self.inputHandler = InputHandler(self.output) self.fileHelper = FileHelper(self.output) self.guiHelper = GUIHelper(self.output) def setConfig(self): Config = self.fileHelper.getConfig() self.ipV4 = Config.ip self.port = Config.port def inizializeClient(self, username, password): self.clientObject = ClientObject(username, None, self.ipV4, self.port, "Welcome_Channel") self.connected = False self.password = password def tryConnect(self): try: self.clientObject.socketObject = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.clientObject.socketObject.connect((self.clientObject.ip, self.clientObject.port)) threading.Thread(target=ServerHandler,args=[self.clientObject,self.windows]).start() self.clientObject.socketObject.sendall(self.decEncHelper.stringToBytes("011" + self.clientObject.username + ":" + self.password)) self.connected = True except: self.connected = False def sendInput(self, message): if self.connected: if str(message).startswith("/"): self.inputHandler.handleInput(str(message[1:]), self.clientObject) else: self.output.append("you: " + message) try: self.clientObject.socketObject.sendall(self.decEncHelper.stringToBytes("001" + message)) except: self.connected = False else: self.guiHelper.printOutput("not connected") def __init__(self, username, password, windows): #Imports self.windows = windows self.output = self.windows[0].output self.importScripts() #Config self.setConfig() #Client initializations self.inizializeClient(username, password) #Client trying to establish a connection self.tryConnect()
def createCard(self): self.verifyEntry() if self.creatCardBool: rank = str(self.rankEntry.get()) if len(rank) < 2: rank = "0" + rank quantity = str(self.quantityEntry.get()) if len(quantity) < 2: quantity = "0" + quantity atkPoints = str(self.atkPointsEntry.get()) if len(atkPoints) == 1: atkPoints = "000" + atkPoints elif len(atkPoints) == 2: atkPoints = "00" + atkPoints elif len(atkPoints) == 3: atkPoints = "0" + atkPoints defPoints = str(self.defPointsEntry.get()) if len(defPoints) == 1: defPoints = "000" + defPoints elif len(defPoints) == 2: defPoints = "00" + defPoints elif len(defPoints) == 3: defPoints = "0" + defPoints card = Card(str(self.nameEntry.get()), str(self.cardEntryVariable.get()), rank, str(self.typeEntryVariable.get()), str(self.attributeEntryVariable.get()), str(self.speedDuelEntryVariable.get()), atkPoints, defPoints, quantity) FileHelper().saveCard(card) self.cardList.append(card) self.cardCreatorWindow.destroy() FileHelper().backupCards() try: if self.mode.get() == 1: self.createCardCreatorWindow(self.cardList, self.mode) except AttributeError: var = None self.creatCardBool = True
def __init__(self): msg = QMessageBox() msg.setText("Hinweis: Nur Codes Deutscher Karten verwenden.") msg.exec() super(Main, self).__init__() self.mainWindow = uic.loadUi("CardOrganizer3.ui", self) self.cardList = FileHelper().loadCards() self.codeEntry = self.mainWindow.codeEntry self.quantityEntry = self.mainWindow.quantityEntry self.speedDualEntry = self.mainWindow.speedDualEntry self.mainWindow.addButton.clicked.connect(self.addCard)
def __init__(self): self.cardList = FileHelper().loadCards() self.app = QApplication([]) msg = QMessageBox() msg.setText("Hinweis: Nur Codes Deutscher Karten verwenden.") msg.exec() window = QWidget() layout = QGridLayout() self.codeEntry = QLineEdit() self.quantityEntry = QLineEdit() self.speedDualEntry = QCheckBox("Speed Dual") addButton = QPushButton("Hinzufügen") addButton.clicked.connect(self.addCard) self.trapCardsTable = QTableWidget() rows = 0 for card in self.cardList: if card.cardObject == "trap": rows = rows + 1 self.trapCardsTable.setRowCount(rows) self.trapCardsTable.setColumnCount(5) self.trapCardsTable.setHorizontalHeaderLabels( ["Name:", "Typ:", "Text:", "Speed Dual:", "Anzahl:"]) self.trapCardsTable.setSortingEnabled(True) self.trapCardsTable.resizeColumnsToContents() self.trapCardsTable.resizeRowsToContents() header = self.trapCardsTable.horizontalHeader() header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents) header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents) header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents) header.setSectionResizeMode(4, QtWidgets.QHeaderView.ResizeToContents) count = 0 for card in self.cardList: if card.cardObject == "trap": self.trapCardsTable.setItem(count, 0, QTableWidgetItem(card.name)) self.trapCardsTable.setItem(count, 1, QTableWidgetItem(card.trapType)) self.trapCardsTable.setItem(count, 2, QTableWidgetItem(card.text)) self.trapCardsTable.setItem(count, 3, QTableWidgetItem(card.speedDuel)) self.trapCardsTable.setItem(count, 4, QTableWidgetItem(card.quantity)) count = count + 1 self.spellCardsTable = QTableWidget() rows = 0 for card in self.cardList: if card.cardObject == "spell": rows = rows + 1 self.spellCardsTable.setRowCount(rows) self.spellCardsTable.setColumnCount(5) self.spellCardsTable.setHorizontalHeaderLabels( ["Name:", "Typ:", "Text:", "Speed Dual:", "Anzahl:"]) self.spellCardsTable.setSortingEnabled(True) self.spellCardsTable.resizeColumnsToContents() self.spellCardsTable.resizeRowsToContents() header = self.spellCardsTable.horizontalHeader() header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents) header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents) header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents) header.setSectionResizeMode(4, QtWidgets.QHeaderView.ResizeToContents) count = 0 for card in self.cardList: if card.cardObject == "spell": self.spellCardsTable.setItem(count, 0, QTableWidgetItem(card.name)) self.spellCardsTable.setItem(count, 1, QTableWidgetItem(card.spellType)) self.spellCardsTable.setItem(count, 2, QTableWidgetItem(card.text)) self.spellCardsTable.setItem(count, 3, QTableWidgetItem(card.speedDuel)) self.spellCardsTable.setItem(count, 4, QTableWidgetItem(card.quantity)) count = count + 1 self.monsterCardsTable = QTableWidget() rows = 0 for card in self.cardList: if card.cardObject == "monster": rows = rows + 1 self.monsterCardsTable.setRowCount(rows) self.monsterCardsTable.setColumnCount(10) self.monsterCardsTable.setHorizontalHeaderLabels([ "Name:", "Attribut:", "Level:", "Monstertyp:", "Kartentyp:", "ATK:", "DEF:", "Text:", "Speed Duel:", "Anzahl:" ]) self.monsterCardsTable.setSortingEnabled(True) self.monsterCardsTable.resizeColumnsToContents() self.monsterCardsTable.resizeRowsToContents() header = self.monsterCardsTable.horizontalHeader() header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents) header.setSectionResizeMode(1, QtWidgets.QHeaderView.ResizeToContents) header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents) header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents) header.setSectionResizeMode(4, QtWidgets.QHeaderView.ResizeToContents) header.setSectionResizeMode(5, QtWidgets.QHeaderView.ResizeToContents) header.setSectionResizeMode(6, QtWidgets.QHeaderView.ResizeToContents) header.setSectionResizeMode(8, QtWidgets.QHeaderView.ResizeToContents) header.setSectionResizeMode(9, QtWidgets.QHeaderView.ResizeToContents) count = 0 for card in self.cardList: if card.cardObject == "monster": self.monsterCardsTable.setItem(count, 0, QTableWidgetItem(card.name)) self.monsterCardsTable.setItem( count, 1, QTableWidgetItem(card.attribute)) self.monsterCardsTable.setItem(count, 2, QTableWidgetItem(card.level)) self.monsterCardsTable.setItem( count, 3, QTableWidgetItem(card.monsterType)) self.monsterCardsTable.setItem(count, 4, QTableWidgetItem(card.cardType)) self.monsterCardsTable.setItem( count, 5, QTableWidgetItem(card.atkPoints)) self.monsterCardsTable.setItem( count, 6, QTableWidgetItem(card.defPoints)) self.monsterCardsTable.setItem(count, 7, QTableWidgetItem(card.text)) self.monsterCardsTable.setItem( count, 8, QTableWidgetItem(card.speedDuel)) self.monsterCardsTable.setItem(count, 9, QTableWidgetItem(card.quantity)) count = count + 1 layout.addWidget(QLabel('Karten Code:'), 0, 0) layout.addWidget(self.codeEntry, 0, 1) layout.addWidget(self.speedDualEntry, 2, 0) layout.addWidget(QLabel("Anzahl:"), 1, 0) layout.addWidget(self.quantityEntry, 1, 1) layout.addWidget(addButton, 3, 0) trapCardsLabel = QLabel("Fallen Karten:") trapCardsLabel.setStyleSheet('color: purple') layout.addWidget(trapCardsLabel, 4, 0) spellCardsLabel = QLabel("Zauber Karten:") spellCardsLabel.setStyleSheet('color: green') layout.addWidget(spellCardsLabel, 4, 1) layout.addWidget(self.trapCardsTable, 5, 0) layout.addWidget(self.spellCardsTable, 5, 1) monsterCardsLabel = QLabel("Monster Karten:") monsterCardsLabel.setStyleSheet('color: #662907') layout.addWidget(monsterCardsLabel, 6, 0) layout.addWidget(self.monsterCardsTable, 7, 0, 8, 0) window.setLayout(layout) window.show() self.app.exec_()
def addCard( self ): #make ad many function eg code,code,code all with quanitity given codeList = list() quantity = self.quantityEntry.text() code = self.codeEntry.text() codes = code.split(",") for code in codes: codeList.append(code) if len(code) == 0: msg = QMessageBox() msg.setText("Fehler: Code darf nicht leer sein.") msg.exec() else: if len(quantity) == 0: msg = QMessageBox() msg.setText("Fehler: Anzahl darf nicht leer sein.") msg.exec() else: if str(quantity).isdigit(): if self.speedDualEntry.isChecked(): speedDuel = "Jan" else: speedDuel = "Nein" for code in codeList: url = "https://www.db.yugioh-card.com/yugiohdb/card_search.action?ope=1&sess=1&keyword=" + code + "&stype=4&ctype=&starfr=&starto=&pscalefr=&pscaleto=&linkmarkerfr=&linkmarkerto=&link_m=2&atkfr=&atkto=&deffr=&defto=&othercon=2" if platform == "darwin": driver = webdriver.Chrome( "/Users/jangj/Desktop/OneDrive/Desktop/Workspace/Privat/Python/Leonard/CardOrganizer2/chromedriver" ) elif platform == "win32": driver = webdriver.Chrome( "B:\Programme\cardsorter2\chromedriver.exe") driver.get(url) typeOfCard = driver.find_element_by_class_name( "box_card_attribute") if typeOfCard.text == "FALLE": nameSourced = driver.find_element_by_class_name( "card_status") name = nameSourced.text name = str(name).replace("\n", "") name = str(name).replace(":", "") trapType = "Normal" try: trapTypeSourced = driver.find_element_by_class_name( "box_card_effect") trapType = trapTypeSourced.text except: var = None textSourced = driver.find_element_by_class_name( "box_card_text") text = textSourced.text text = str(text).replace("\n", "") text = str(text).replace(":", "") if "\u25cf" in text: text = str(text).replace("\u25cf", "-") trapCardObject = TrapCard("trap", name, trapType, text, speedDuel, quantity) for card in self.cardList: if card.name == trapCardObject.name: msg = QMessageBox( ) #TODO:add buttons with add quantity that was given, add card as new uniq, not add msg.setText( "Hinweis: Fallen Karte mit dem selben Namen exisitert bereits." ) msg.exec() self.cardList.append(trapCardObject) FileHelper().saveCard(trapCardObject) self.addRow(trapCardObject) elif typeOfCard.text == "ZAUBER": nameSourced = driver.find_element_by_class_name( "card_status") name = nameSourced.text name = str(name).replace("\n", "") name = str(name).replace(":", "") spellType = "Normal" try: spellTypeSourced = driver.find_element_by_class_name( "box_card_effect") spellType = spellTypeSourced.text except: var = None textSourced = driver.find_element_by_class_name( "box_card_text") text = textSourced.text text = str(text).replace("\n", "") text = str(text).replace(":", "") if "\u25cf" in text: text = str(text).replace("\u25cf", "-") spellCardObject = SpellCard( "spell", name, spellType, text, speedDuel, quantity) for card in self.cardList: if card.name == spellCardObject.name: msg = QMessageBox( ) #TODO:add buttons with add quantity that was given, add card as new uniq, not add msg.setText( "Hinweis: Zauber Karte mit dem selben Namen exisitert bereits." ) msg.exec() self.cardList.append(spellCardObject) FileHelper().saveCard(spellCardObject) self.addRow(spellCardObject) else: nameSourced = driver.find_element_by_class_name( "card_status") name = nameSourced.text name = str(name).replace("\n", "") name = str(name).replace(":", "") attributeSourced = driver.find_element_by_class_name( "box_card_attribute") attribute = attributeSourced.text try: levelSourced = driver.find_element_by_css_selector( "span.box_card_level_rank.level") level = levelSourced.text except: try: levelSourced = driver.find_element_by_class_name( "box_card_linkmarker") level = levelSourced.text except: var = None infoSourced = driver.find_element_by_class_name( "card_info_species_and_other_item") info = infoSourced.text info = str(info).strip("[") info = str(info).strip("]") info = str(info).strip() info = str(info).split("/") if len(info) == 1: monsterType = info[0] cardType = "Normal" elif len(info) == 2: monsterType = info[0] cardType = str(info[1]).strip() else: monsterType = info[0] cardType = str(info[1]).strip() + "/" + str( info[2]).strip() atkPointsSourced = driver.find_element_by_class_name( "atk_power") atkPoints = atkPointsSourced.text atkPoints = str(atkPoints).replace("ATK ", "") defPointsSourced = driver.find_element_by_class_name( "def_power") defPoints = defPointsSourced.text defPoints = str(defPoints).replace("DEF ", "") textSourced = driver.find_element_by_class_name( "box_card_text") text = textSourced.text text = str(text).replace("\n", "") text = str(text).replace(":", "") if "\u25cf" in text: text = str(text).replace("\u25cf", "-") monsterCardObject = MonsterCard( "monster", name, attribute, level, monsterType, cardType, atkPoints, defPoints, text, speedDuel, quantity) for card in self.cardList: if card.name == monsterCardObject.name: msg = QMessageBox( ) #TODO:add buttons with add quantity that was given, add card as new uniq, not add msg.setText( "Hinweis: Monster Karte mit dem selben Namen exisitert bereits." ) msg.exec() self.cardList.append(monsterCardObject) FileHelper().saveCard(monsterCardObject) self.addRow(monsterCardObject) driver.close() FileHelper().backupCards() self.codeEntry.setText("") self.quantityEntry.setText("") else: msg = QMessageBox() msg.setText("Fehler: Anzahl muss eine Zahl sein.") msg.exec()
def handle( self ): #overwrite TODO: find a way to import script only once not once per handle call self.decEncHelper = DecodingEncodingHelper() self.channelManager = ChannelManager() self.clientManager = ClientManager() self.mysqlHelper = MysqlHelper() self.fileHelper = FileHelper() self.logHelper = LogHelper() if self.appendClient: self.clientObject = Client(self.request, "*NOT_ASSIGNED*", "*NOT_ASSIGNED*", "*NOT_ASSIGNED*") if len(self.fileHelper.readTXTFile("data/", "banList")) > 1: for client in self.fileHelper.readTXTFile("data/", "banList"): try: banTime = client.split(":")[1] except IndexError: pass if self.clientObject.ip + "\n" == client: self.logHelper.log( "info", self.clientObject.ip + ":" + str(self.clientObject.port) + " is permanantly banned on the server") self.clientObject.socketObject.sendall( self.decEncHelper.stringToBytes( "405[Client/Info] You are permanantly banned on this server" )) self.clientObject.socketObject.close() self.appendClient = False elif self.clientObject.ip + ":" + banTime == client: currentTimeStamp = datetime.datetime.now().timestamp() banTime = banTime[:-1] if (currentTimeStamp > float(banTime)): self.fileHelper.removeClientFromBanList( self.clientObject.ip) self.clientManager.addClient(self.clientObject) self.logHelper.log( "info", str(self.clientObject.ip) + ":" + str(self.clientObject.port) + " connected to the server") print( self.mysqlHelper.getAccountRank( self.clientObject)) if len( self.mysqlHelper.getAccountRank( self.clientObject)) < 3: self.clientObject.rank = "user" self.mysqlHelper.updateAccountRank( self.clientObject) self.appendClient = False self.tryRecv = True else: self.logHelper.log( "info", self.clientObject.ip + ":" + str(self.clientObject.port) + " is temporary banned on the server. Remaining Time: " + str( int((float(banTime) - currentTimeStamp) / 60)) + "Minutes") self.clientObject.socketObject.sendall( self.decEncHelper.stringToBytes( "405[Client/Info] You are temporary banned on this server. Remaining Time: " + str( int((float(banTime) - currentTimeStamp) / 60)) + " Minutes")) self.channelManager.removeChannelMember( self.clientObject.channelObject, self.clientObject) self.clientObject.socketObject.close() self.appendClient = False break elif "BanList:\n" == client: pass else: self.clientManager.addClient(self.clientObject) self.logHelper.log( "info", str(self.clientObject.ip) + ":" + str(self.clientObject.port) + " connected to the server.") self.appendClient = False self.tryRecv = True else: self.clientManager.addClient(self.clientObject) self.logHelper.log( "info", str(self.clientObject.ip) + ":" + str(self.clientObject.port) + " connected to the server.") self.appendClient = False self.tryRecv = True if self.tryRecv: try: self.data = self.decEncHelper.bytesToString( self.clientObject.socketObject.recv(1024)) self.handleRequest(self.data, self.clientObject) except: for clientObjectInList in self.clientManager.clientList: if clientObjectInList != self.clientObject: if self.loggedIn: if self.channelManager.channelContains( clientObjectInList, self.clientObject.channelObject.name): clientObjectInList.socketObject.sendall( self.decEncHelper.stringToBytes( "811[Client/Info] " + self.clientObject.username + " quit.")) self.logHelper.log( "info", self.clientObject.ip + ":" + str(self.clientObject.port) + " Disconnected") self.mysqlHelper.logoutAccount(self.clientObject) self.clientManager.removeClient(self.clientObject) if self.loggedIn: self.channelManager.removeChannelMember( self.clientObject.channelObject, self.clientObject)
class ClientHandler(socketserver.BaseRequestHandler): appendClient = True tryRecv = False loggedIn = False def handle( self ): #overwrite TODO: find a way to import script only once not once per handle call self.decEncHelper = DecodingEncodingHelper() self.channelManager = ChannelManager() self.clientManager = ClientManager() self.mysqlHelper = MysqlHelper() self.fileHelper = FileHelper() self.logHelper = LogHelper() if self.appendClient: self.clientObject = Client(self.request, "*NOT_ASSIGNED*", "*NOT_ASSIGNED*", "*NOT_ASSIGNED*") if len(self.fileHelper.readTXTFile("data/", "banList")) > 1: for client in self.fileHelper.readTXTFile("data/", "banList"): try: banTime = client.split(":")[1] except IndexError: pass if self.clientObject.ip + "\n" == client: self.logHelper.log( "info", self.clientObject.ip + ":" + str(self.clientObject.port) + " is permanantly banned on the server") self.clientObject.socketObject.sendall( self.decEncHelper.stringToBytes( "405[Client/Info] You are permanantly banned on this server" )) self.clientObject.socketObject.close() self.appendClient = False elif self.clientObject.ip + ":" + banTime == client: currentTimeStamp = datetime.datetime.now().timestamp() banTime = banTime[:-1] if (currentTimeStamp > float(banTime)): self.fileHelper.removeClientFromBanList( self.clientObject.ip) self.clientManager.addClient(self.clientObject) self.logHelper.log( "info", str(self.clientObject.ip) + ":" + str(self.clientObject.port) + " connected to the server") print( self.mysqlHelper.getAccountRank( self.clientObject)) if len( self.mysqlHelper.getAccountRank( self.clientObject)) < 3: self.clientObject.rank = "user" self.mysqlHelper.updateAccountRank( self.clientObject) self.appendClient = False self.tryRecv = True else: self.logHelper.log( "info", self.clientObject.ip + ":" + str(self.clientObject.port) + " is temporary banned on the server. Remaining Time: " + str( int((float(banTime) - currentTimeStamp) / 60)) + "Minutes") self.clientObject.socketObject.sendall( self.decEncHelper.stringToBytes( "405[Client/Info] You are temporary banned on this server. Remaining Time: " + str( int((float(banTime) - currentTimeStamp) / 60)) + " Minutes")) self.channelManager.removeChannelMember( self.clientObject.channelObject, self.clientObject) self.clientObject.socketObject.close() self.appendClient = False break elif "BanList:\n" == client: pass else: self.clientManager.addClient(self.clientObject) self.logHelper.log( "info", str(self.clientObject.ip) + ":" + str(self.clientObject.port) + " connected to the server.") self.appendClient = False self.tryRecv = True else: self.clientManager.addClient(self.clientObject) self.logHelper.log( "info", str(self.clientObject.ip) + ":" + str(self.clientObject.port) + " connected to the server.") self.appendClient = False self.tryRecv = True if self.tryRecv: try: self.data = self.decEncHelper.bytesToString( self.clientObject.socketObject.recv(1024)) self.handleRequest(self.data, self.clientObject) except: for clientObjectInList in self.clientManager.clientList: if clientObjectInList != self.clientObject: if self.loggedIn: if self.channelManager.channelContains( clientObjectInList, self.clientObject.channelObject.name): clientObjectInList.socketObject.sendall( self.decEncHelper.stringToBytes( "811[Client/Info] " + self.clientObject.username + " quit.")) self.logHelper.log( "info", self.clientObject.ip + ":" + str(self.clientObject.port) + " Disconnected") self.mysqlHelper.logoutAccount(self.clientObject) self.clientManager.removeClient(self.clientObject) if self.loggedIn: self.channelManager.removeChannelMember( self.clientObject.channelObject, self.clientObject) def handleRequest(self, request, clientObject): requestId = request[:3] requestdata = request[3:] if requestId == "001": #chatting self.logHelper.channelLog( "info", clientObject.channelObject.name, clientObject.ip + ":" + str(clientObject.port) + " [" + clientObject.rank + "]" + clientObject.username + " : " + requestdata) for clientObjectFromList in self.clientManager.clientList: if clientObjectFromList.channelObject.name == clientObject.channelObject.name: if clientObjectFromList != clientObject: clientObjectFromList.socketObject.sendall( self.decEncHelper.stringToBytes( "001[" + clientObject.rank + "]" + clientObject.username + " : " + requestdata)) elif requestId == "011": #try logging in requestdata = requestdata.split(":") self.logHelper.log( "info", str(self.clientObject.ip) + ":" + str(self.clientObject.port) + " tried logging in.") self.clientManager.updateClientUsername(clientObject, requestdata[0]) if self.mysqlHelper.tryLogin(clientObject, requestdata[1]): self.loggedIn = True self.clientObject.channelObject = self.channelManager.channelList[ 0] self.clientObject.channelObject.clientList.append( self.clientObject) self.clientManager.updateClientRank( clientObject, self.mysqlHelper.getAccountRank(clientObject)) for clientObjectInList in self.clientManager.clientList: if clientObjectInList != clientObject: if self.channelManager.channelContains( clientObjectInList, "Welcome_Channel"): clientObjectInList.socketObject.sendall( self.decEncHelper.stringToBytes( "811[" + clientObject.rank + "]" + clientObject.username + " joined.")) self.logHelper.log( "info", str(self.clientObject.ip) + ":" + str(self.clientObject.port) + " logged in as " + clientObject.username + " succesfully.") if len(self.mysqlHelper.getAccountRank(self.clientObject)) < 3: self.clientObject.rank = "user" self.mysqlHelper.updateAccountRank(self.clientObject) for clientObjectInList in self.clientManager.clientList: if clientObjectInList != clientObject: if self.channelManager.channelContains( clientObjectInList, "Welcome_Channel"): clientObjectInList.socketObject.sendall( self.decEncHelper.stringToBytes( "811[" + clientObject.rank + "]" + clientObject.username + " joined.")) clientObject.socketObject.sendall( self.decEncHelper.stringToBytes("903")) else: self.logHelper.log( "info", str(self.clientObject.ip) + ":" + str(self.clientObject.port) + " couldn't log in.") self.clientObject.socketObject.sendall( self.decEncHelper.stringToBytes("902")) self.clientObject.socketObject.close() elif requestId == "611": #sent current clients in given channel self.logHelper.log( "info", str(self.clientObject.ip) + ":" + str(self.clientObject.port) + " " + clientObject.username + " requested the clients from channel " + requestdata + ".") for channel in self.channelManager.channelList: if channel.name == requestdata: if len(channel.clientList) < 1: self.clientObject.socketObject.sendall( self.decEncHelper.stringToBytes("611Empty")) else: clientsInChannel = list() for client in channel.clientList: clientsInChannel.append(client.username) self.clientObject.socketObject.sendall( self.decEncHelper.stringToBytes( "611" + requestdata + ";" + str(clientsInChannel))) break elif requestId == "541": #sent client rank self.logHelper.log( "info", clientObject.ip + " " + clientObject.username + " requested rank.") self.clientObject.socketObject.sendall( self.decEncHelper.stringToBytes("541" + str(self.clientObject.rank))) elif requestId == "022": #channel request self.logHelper.log( "info", clientObject.ip + " " + clientObject.username + " requested channel.") channelNames = list() channelDescriptions = list() channelPasswords = list() channelAccessLevels = list() for channelObject in self.channelManager.channelList: channelNames.append(channelObject.name) channelDescriptions.append(channelObject.description) channelPasswords.append(channelObject.password) channelAccessLevels.append(channelObject.accessLevel) self.clientObject.socketObject.sendall( self.decEncHelper.stringToBytes("022" + str(channelNames) + ":" + str(channelDescriptions) + ":" + str(channelPasswords) + ":" + str(channelAccessLevels))) elif requestId == "023": #changing channels if self.channelManager.channelExists(requestdata): if self.channelManager.channelContains(self.clientObject, requestdata): clientObject.socketObject.sendall( self.decEncHelper.stringToBytes( "023[Client/Info] you are already in this channel." )) self.logHelper.log( "info", clientObject.ip + ":" + str(clientObject.port) + " " + clientObject.username + " tried to join a channel which he is already part of." ) else: for channelObject in self.channelManager.channelList: if channelObject.name == requestdata: oldChannel = clientObject.channelObject.name self.channelManager.removeChannelMember( clientObject.channelObject, clientObject) clientObject.channelObject = channelObject self.channelManager.addChannelMember( channelObject, clientObject) clientObject.socketObject.sendall( self.decEncHelper.stringToBytes( "023[Client/Info] You succesfully changed to " + requestdata + ".")) self.logHelper.log( "info", clientObject.ip + ":" + str(clientObject.port) + " " + clientObject.username + " changed from " + oldChannel + " to " + requestdata + ".") for clientInList in self.clientManager.clientList: clientInList.socketObject.sendall( self.decEncHelper.stringToBytes("811")) else: clientObject.socketObject.sendall( self.decEncHelper.stringToBytes( "023[Client/Info] This Channel doesn't exists.")) self.logHelper.log( "info", clientObject.ip + " : " + clientObject.username + " tried to join a channel that doesn't exists.") elif requestId == "031": #changing namesFIXME: doesnt work with rank not tested witohut if self.clientManager.hasRank(clientObject, "admin"): self.fileHelper.removeClientRank(clientObject) clientObject.username = requestdata self.fileHelper.addClientRank(clientObject, "admin") clientObject.socketObject.sendall( self.decEncHelper.stringToBytes( "031[Client/Info] you succesfully changed your name.")) self.logHelper.log( "info", clientObject.ip + ":" + str(clientObject.port) + " " + clientObject.username + " changed name.") else: clientObject.socketObject.sendall( self.decEncHelper.stringToBytes( "031[Client/Info] You don't have access to that command." )) self.logHelper.log( "info", clientObject.ip + ":" + str(clientObject.port) + " " + clientObject.username + " had no access to that command. Rank:(" + clientObject.rank.strip("\n") + ")") elif requestId == "411": #kicking clients if self.clientManager.hasRank(clientObject, "admin"): if self.clientManager.usernameExists(requestdata): if requestdata == self.clientObject.username: clientObject.socketObject.sendall( self.decEncHelper.stringToBytes( "411[Client/Info] You can't kick yourself.")) else: for clientObjectInList in self.clientManager.clientList: if clientObjectInList.username == requestdata: clientObjectInList.socketObject.sendall( self.decEncHelper.stringToBytes( "402[Client/Info] You got kicked by: " + self.clientObject.username)) clientObjectInList.socketObject.close() time.sleep(0.1) self.logHelper.log( "info", clientObject.ip + ":" + str(clientObject.port) + " " + clientObject.username + " kicked : " + requestdata) clientObject.socketObject.sendall( self.decEncHelper.stringToBytes( "411[Client/Info] You sucessfully kicked: " + requestdata)) break elif self.clientManager.ipExists(requestdata): if requestdata == self.clientObject.ip: clientObject.socketObject.sendall( self.decEncHelper.stringToBytes( "411[Client/Info] You can't kick yourself.")) else: for clientObjectInList in self.clientManager.clientList: if clientObjectInList.ip == requestdata: clientObjectInList.socketObject.sendall( self.decEncHelper.stringToBytes( "402[Client/Info] You got kicked by: " + self.clientObject.username)) clientObjectInList.socketObject.close() self.logHelper.log( "info", clientObject.ip + ":" + str(clientObject.port) + " " + clientObject.username + " kicked : " + requestdata) clientObject.socketObject.sendall( self.decEncHelper.stringToBytes( "411[Client/Info] You sucessfully kicked: " + requestdata)) break else: clientObject.socketObject.sendall( self.decEncHelper.stringToBytes( "411[Client/Info] Username or ip doesnt exists on the server." )) else: clientObject.socketObject.sendall( self.decEncHelper.stringToBytes( "031[Client/Info] You don't have access to that command." )) self.logHelper.log( "info", clientObject.ip + ":" + str(clientObject.port) + " " + clientObject.username + " had no access to that command. Rank:(" + clientObject.rank.strip("\n") + ")") elif requestId == "711": #banning clients if self.clientManager.hasRank(clientObject, "admin"): requestdata = requestdata.split() client = requestdata[0] banTime = requestdata[1] if self.clientManager.usernameExists(client): if client == self.clientObject.username: clientObject.socketObject.sendall( self.decEncHelper.stringToBytes( "711[Client/Info] You can't ban yourself.")) else: for clientObjectInList in self.clientManager.clientList: if clientObjectInList.username == client: if banTime == 0: self.fileHelper.addClientToBanList( clientObjectInList.ip) self.logHelper.log( "info", clientObjectInList.ip + ":" + str(clientObjectInList.port) + " " + clientObjectInList.username + " got permanantly banned by " + clientObject.username) clientObjectInList.socketObject.sendall( self.decEncHelper.stringToBytes( "711" + "[Client/Info] You got permanantly banned by " + clientObject.username)) clientObjectInList.socketObject.close() clientObject.socketObject.sendall( self.decEncHelper.stringToBytes( "711[Client/Info] You sucessfully banned: " + clientObjectInList.username)) else: currentTimeStamp = datetime.datetime.now( ).timestamp() self.fileHelper.addClientToBanList( clientObjectInList.ip + ":" + str(currentTimeStamp + int(banTime) * 60)) self.logHelper.log( "info", clientObjectInList.ip + ":" + str(clientObjectInList.port) + " " + clientObjectInList.username + " got banned for " + str(banTime) + "minutes by " + clientObject.username) clientObjectInList.socketObject.sendall( self.decEncHelper.stringToBytes( "711" + "[Client/Info] You got banned for " + str(banTime) + "Minutes by " + clientObject.username)) clientObjectInList.socketObject.close() clientObject.socketObject.sendall( self.decEncHelper.stringToBytes( "711[Client/Info] You sucessfully banned: " + clientObjectInList.username + " for " + str(banTime))) elif self.clientManager.ipExists(client): if client == self.clientObject.ip: clientObject.socketObject.sendall( self.decEncHelper.stringToBytes( "711[Client/Info] You can't ban yourself.")) else: for clientObjectInList in self.clientManager.clientList: if clientObjectInList.ip == client: if banTime == 0: self.fileHelper.addClientToBanList( clientObjectInList.ip) self.logHelper.log( "info", clientObjectInList.ip + ":" + str(clientObjectInList.port) + " " + clientObjectInList.username + " got permanantly banned by " + clientObject.username) clientObjectInList.socketObject.sendall( self.decEncHelper.stringToBytes( "711" + "[Client/Info] You got permanantly banned by " + clientObject.username)) clientObjectInList.socketObject.close() clientObject.socketObject.sendall( self.decEncHelper.stringToBytes( "711[Client/Info] You sucessfully banned: " + clientObjectInList.username)) else: currentTimeStamp = datetime.datetime.now( ).timestamp() self.fileHelper.addClientToBanList( clientObjectInList.ip + ":" + str(currentTimeStamp + int(banTime) * 60)) self.logHelper.log( "info", clientObjectInList.ip + ":" + str(clientObjectInList.port) + " " + clientObjectInList.username + " got banned for " + str(banTime) + "minutes by " + clientObject.username) clientObjectInList.socketObject.sendall( self.decEncHelper.stringToBytes( "711" + "[Client/Info] You got banned for " + str(banTime) + "Minutes by " + clientObject.username)) clientObjectInList.socketObject.close() clientObject.socketObject.sendall( self.decEncHelper.stringToBytes( "711[Client/Info] You sucessfully banned: " + clientObjectInList.username + " for " + str(banTime))) else: clientObject.socketObject.sendall( self.decEncHelper.stringToBytes( "711[Client/Info] Username or ip doesnt exists on the server." )) else: clientObject.socketObject.sendall( self.decEncHelper.stringToBytes( "031[Client/Info] You don't have access to that command." )) self.logHelper.log( "info", clientObject.ip + ":" + str(clientObject.port) + " " + clientObject.username + " had no access to that command. Rank:(" + clientObject.rank.strip("\n") + ")") elif requestId == "901": #GUI get all channel with clients channelList = list() for channel in self.channelManager.channelList: memberList = list() for client in channel.clientList: if client.username == clientObject.username: memberList.append(client.username + "(you)") else: memberList.append(client.username) channelList.append(channel.name + ":" + str(memberList) + ";") clientObject.socketObject.sendall( self.decEncHelper.stringToBytes("901" + str(channelList))) else: #any other requestId if len(requestId) == 0: raise SystemExit() else: clientObject.socketObject.sendall( self.decEncHelper.stringToBytes( "401[Client/Error] Unknown request ID")) self.logHelper.log( "error", clientObject.ip + ":" + str(clientObject.port) + " sent unknown request ID") self.handle()
def backupCardFileDataButton(self): FileHelper().backupCards() messagebox.showinfo("Info", "Backup wurde erstellt.")
def __init__(self): self.fileHelper = FileHelper() self.logHelper = LoggingHelper() self.clients = Clients()
class MysqlHelper: def __init__(self): self.fileHelper = FileHelper() self.logHelper = LogHelper() config = self.fileHelper.getConfig("Mysql Server Config") try: self.connection = mysql.connector.connect(user=config.username, password=config.password, host=config.ip, database=config.database) except: print("Couldn't establish connection to mysql database(" + config.database + ") with ip: " + config.ip) #TODO: find a way to handle with this def ExecuteCommand(self, command): result = None try: result = MysqlStatement( command, self.connection).execute().escape().fetchall().result except AttributeError: self.logHelper.log("info", "Created mysql table.") self.ExecuteCommandWithoutFetchAndResult( "CREATE TABLE accounts ( id INT NOT NULL AUTO_INCREMENT, username TEXT NOT NULL, password TEXT NOT NULL, email TEXT NOT NULL, rank TEXT NOT NULL, loggedIn TINYINT NOT NULL DEFAULT '0', PRIMARY KEY (id))" ) return result def ExecuteCommandWithoutFetchAndResult(self, command): return MysqlStatement(command, self.connection).execute().escape().commit() def tryLogin(self, clientObject, password): #TODO: give better fedback for layer 8 result = False lenght = None try: lenght = len( self.ExecuteCommand( "SELECT * FROM accounts WHERE username = '******'")) except: lenght = len( self.ExecuteCommand( "SELECT * FROM accounts WHERE username = '******'")) if lenght > 0: if self.ExecuteCommand( "select loggedIn,(case when loggedIn = 0 then 'loggedOut' when loggedIn = 1 then 'loggedIn' end) as loggedIn_status FROM accounts WHERE username = '******'")[0][1] != "loggedIn": if len( self.ExecuteCommand( "SELECT * FROM accounts WHERE username = '******' and password = '******'")) > 0: self.ExecuteCommandWithoutFetchAndResult( "UPDATE accounts SET loggedIn = 1 WHERE username = '******'") result = True return result def logoutAccount(self, clientObject): self.ExecuteCommandWithoutFetchAndResult( "UPDATE accounts SET loggedIn = 0 WHERE username = '******'") def getAccountRank(self, clientObject): return self.ExecuteCommand( "SELECT rank FROM accounts WHERE username = '******'")[0][0] def updateAccountRank(self, clientObject): self.ExecuteCommandWithoutFetchAndResult( "UPDATE accounts SET rank = '" + clientObject.rank + "' WHERE username = '******'")
def __init__(self): FileHelper().backupCards() MainWindow().createMainWindow()
def importScripts(self): self.decEncHelper = DecodingEncodingHelper() self.inputHandler = InputHandler(self.output) self.fileHelper = FileHelper(self.output) self.guiHelper = GUIHelper(self.output)
class Server: def importScripts(self): self.decEncHelper = DecodingEncodingHelper() self.channelManager = ChannelManager() self.clientManager = ClientManager() self.inputHandler = InputHandler(self.upTime) self.fileHelper = FileHelper() self.logHelper = LogHelper() def setConfig(self): config = self.fileHelper.getConfig("Server Config") self.port = config.port self.ipV4 = config.ip def inizializeChannel(self): self.welcomeChannel = Channel("Welcome_Channel", "welcome to the server", "No", 0, list()) self.channel1 = Channel("Channel_1", "Description of channel 1", "No", 0, list()) self.channel2 = Channel("Channel_2", "Description of channel 1", "No", 0, list()) self.channel3 = Channel("Channel_3", "Description of channel 1", "No", 0, list()) self.channelManager.addChannel(self.welcomeChannel) self.channelManager.addChannel(self.channel1) self.channelManager.addChannel(self.channel2) self.channelManager.addChannel(self.channel3) def inizializeServer(self): self.server = ServerThread((self.ipV4, self.port), ClientHandler) serverThread = threading.Thread(target=self.server.serve_forever) serverThread.daemon = True serverThread.start() self.logHelper.log("info" ,"Started server (version: " + self.fileHelper.getConfig("Version") + ") on ip: " + self.ipV4 + " port: " + str(self.port)) def askForInput(self): while True: try: command = input() except KeyboardInterrupt: self.logHelper.log("info", "Gracefully stopping server...") if len(self.clientManager.clientList) < 1: self.logHelper.log("info", "Gracefully stopped server") break else: for clientObject in self.clientManager.clientList: clientObject.socketObject.sendall(self.decEncHelper.stringToBytes("403")) self.logHelper.log("info", "Gracefully stopped server") break if str(command).startswith("/"): try: self.inputHandler.handleInput(str(command[1:]).lower()) except IndexError: self.logHelper.log("info", "type /help for a list of commands.") else: self.logHelper.log("info", "Commands always start with (/)") def __init__(self): self.upTime = time.time() #Imports self.importScripts() #Config self.setConfig() #Channel initialization self.inizializeChannel() #Server initializations self.inizializeServer() #Console Input self.askForInput()
class InputHandler: CommandList = dict() fileHelper = None logHelper = None clients = None #helper def BytesToString(self, bytes): return str(bytes, "utf-8") def StringToBytes(self, string): return bytes(string, "utf-8") def __init__(self): self.fileHelper = FileHelper() self.logHelper = LoggingHelper() self.clients = Clients() def handleInput(self, command): command = command.split() if command[0] == "clear": os.system('cls' if os.name == 'nt' else 'clear') elif command[0] == "listClients": if len(self.clients.clientList) < 1: self.logHelper.printAndWriteServerLog( "[Server/Error] No clients connected") else: self.logHelper.printAndWriteServerLog( "[Server/Info] Connected clients:") for client in self.clients.clientList: for key in client.keys(): self.logHelper.printAndWriteServerLog( "[Server/Info] " + str(key.getpeername()) + " : " + str(client[key])) elif command[0] == "kick": try: user = command[1] if len(self.clients.clientList) < 1: self.logHelper.printAndWriteServerLog( "[Server/Error] No clients connected") else: for client in self.clients.clientList: for key in client.keys(): if key.getpeername()[0] == user: self.logHelper.printAndWriteServerLog( "[Server/Info] " + user + " : " + client[key] + " got kicked") key.sendall( self.StringToBytes( "402" + "[Client/Info] You got kicked by the console" )) key.close() else: self.logHelper.printAndWriteServerLog( "[Server/Error] No client with ip: " + user) except IndexError: self.logHelper.printAndWriteServerLog( "[Server/Info] /kick <client>") elif command[0] == "ban": try: time = 0 user = command[1] permanantly = True try: time = command[2] except: permanantly = True if int(time) > 0: permanantly = False if len(self.clients.clientList) < 1: self.logHelper.printAndWriteServerLog( "[Server/Error] No clients connected") else: for client in self.clients.clientList: for key in client.keys(): if key.getpeername()[0] == user: if permanantly: self.fileHelper.addClientToBanList(user) self.logHelper.printAndWriteServerLog( "[Server/Info] " + user + " : " + client[key] + " got permanantly banned") key.sendall( self.StringToBytes( "405" + "[Client/Info] You got permanantly banned by the console" )) key.close() else: self.fileHelper.addClientToBanList(user + ":" + time) self.logHelper.printAndWriteServerLog( "[Server/Info] " + user + " : " + client[key] + " got banned for " + str(time) + "minutes") key.sendall( self.StringToBytes( "405" + "[Client/Info] You got banned for " + str(time) + "Minutes by the console")) key.close() else: self.logHelper.printAndWriteServerLog( "[Server/Error] No client with ip: " + user) except IndexError: self.logHelper.printAndWriteServerLog( "[Server/Info] /ban <client> <time>") else: self.logHelper.printAndWriteServerLog( "[Server/Error] Unknown command: (" + str(command) + ")") self.logHelper.printAndWriteServerLog( "[Server/Error] type /help for a list of commands")
def handle(self): logHelper = LoggingHelper() fileHelper = FileHelper() self.client = self.request self.clients = Clients() if self.appendClient: logHelper.printAndWriteServerLog("[Server/Info] " + str(self.client_address[0]) + ":" + str(self.client_address[1]) + " connected to the server") for clientInList in fileHelper.readTXTFile("data/", "banList"): clientInListString = clientInList.split(":") try: banTime = clientInListString[1] except IndexError: var = None if self.client_address[0] + "\n" in clientInList: logHelper.printAndWriteServerLog( "[Server/Info] " + str(self.client_address[0]) + ":" + str(self.client_address[1]) + " is permanantly banned on the server") self.client.sendall( self.StringToBytes( "405[Client/Info] You are permanantly banned on this server" )) self.client.close() self.appendClient = False elif self.client_address[0] + ":" + banTime in clientInList: currTime = datetime.datetime.now().timestamp() banTime = banTime[:-1] if (currTime > float(banTime)): print("1") else: print("2") logHelper.printAndWriteServerLog( "[Server/Info] " + str(self.client_address[0]) + ":" + str(self.client_address[1]) + " is temporary banned on the server. Remaining Time: " + str(int((float(banTime) - currTime) / 60)) + "Minutes") self.client.sendall( self.StringToBytes( "405[Client/Info] You are temporary banned on this server. Remaining Time: " + str(int((float(banTime) - currTime) / 60)) + "Minutes")) self.client.close() self.appendClient = False else: self.clients.addClient(self.client, "None") self.appendClient = False try: self.data = self.BytesToString(self.client.recv(1024).strip()) if len(self.data[6:]) == 0: logHelper.printAndWriteServerLog("[Server/Info] " + str(self.client_address[0]) + ":" + str(self.client_address[1]) + " sent client informations") self.handleRequest(self.data, self.client) else: logHelper.printAndWriteChannelLog("[Server/Channel/Info] " + str(self.client_address[0]) + ":" + str(self.client_address[1]) + " " + self.data[3:]) self.handleRequest(self.data, self.client) except: logHelper.printAndWriteServerLog("[Server/Error] " + str(self.client_address[0]) + ":" + str(self.client_address[1]) + " closed connection unexpectedly") self.clients.removeClient(self.client, self.username)
def createStatWindowButton(self): tableViewThread = threading.Thread( target=StatWindow().createStatWindow(FileHelper().loadCards())) tableViewThread.daemon = True tableViewThread.start()
class Client: def importScripts(self): self.decEncHelper = DecodingEncodingHelper() self.inputHandler = InputHandler(self.output) self.fileHelper = FileHelper(self.output) self.guiHelper = GUIHelper(self.output) def setConfig(self): Config = self.fileHelper.getConfig() self.ipV4 = Config.ip self.port = Config.port def inizializeClient(self, username, password): self.clientObject = ClientObject(username, None, self.ipV4, self.port, "Welcome_Channel") self.connected = False self.password = password def button(self): if self.mainWindow.statusButton.text() != "Offline": self.sendInput("/disconnect") self.mainWindow.statusButton.setText("Offline") self.mainWindow.output.clear() self.mainWindow.channelTree.clear() self.connected = False else: data = CustomDialog().getData() if data == ":": self.mainWindow.close() else: data = data.split(":") self.inizializeClient(data[0], data[1]) self.tryConnect() def tryConnect(self): trys = 0 while not self.connected: try: self.clientObject.socketObject = socket.socket( socket.AF_INET, socket.SOCK_STREAM) self.clientObject.socketObject.connect( (self.clientObject.ip, self.clientObject.port)) threading.Thread(target=ServerHandler, args=[self.clientObject, self.mainWindow]).start() self.clientObject.socketObject.sendall( self.decEncHelper.stringToBytes( "011" + self.clientObject.username + ":" + self.password)) self.connected = True except: trys = trys + 1 os.system('cls' if os.name == 'nt' else 'clear') self.guiHelper.printOutput( "[Client/Info] Attempting to connect to server with ip: " + self.clientObject.ip + ". Attempts: " + str(trys)) time.sleep(5) def sendInput(self, message): if self.connected: if str(message).startswith("/"): self.inputHandler.handleInput(str(message[1:]), self.clientObject) else: self.output.append("you: " + message) try: self.clientObject.socketObject.sendall( self.decEncHelper.stringToBytes("001" + message)) except: self.connected = False else: self.guiHelper.printOutput("not connected") def __init__(self, username, password, mainWindow): #Imports self.mainWindow = mainWindow self.mainWindow.statusButton.clicked.connect(self.button) self.output = mainWindow.output self.importScripts() #Config self.setConfig() #Client initializations self.inizializeClient(username, password) #Client trying to establish a connection self.tryConnect()
class MysqlHelper: def __init__(self, announce): self.mysqlMode = 0 # 0 = Mysql; 1 = MysqlLite self.fileHelper = FileHelper() self.logHelper = LogHelper() config = self.fileHelper.getConfig("Mysql Server Config") try: self.connection = mysql.connector.connect(user=config.username, password=config.password, host=config.ip, database=config.database) except: self.mysqlMode = 1 if (announce): print( "[" + datetime.datetime.now().strftime("%H:%M:%S") + " ERROR]: Couldn't establish connection to mysql database(" + config.database + ") with ip: " + config.ip) print("[" + datetime.datetime.now().strftime("%H:%M:%S") + " INFO]: Falling back to MysqlLite.") #sqllite self.conn = self.create_connection("data/database.db") checkForAccountsTable = "SELECT * FROM accounts" result = self.executeCommandOnLite(self.conn, checkForAccountsTable) try: for row in result: if row[0] == 1: result = True else: result = False except: result = False if result == False: createTableStatement = "CREATE TABLE accounts (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL, password TEXT NOT NULL, email TEXT NOT NULL, rank TEXT NOT NULL, loggedIn TINYINT NOT NULL DEFAULT '0');" print("[" + datetime.datetime.now().strftime("%H:%M:%S") + " INFO]: Created accounts table in MysqlLite database.") self.executeCommandOnLite(self.conn, createTableStatement) def create_connection(self, db_file): try: conn = sqlite3.connect(db_file) return conn except Error as e: print(e) return e def executeCommandOnLite(self, connection, command): try: cursor = connection.cursor() result = cursor.execute(command) return result except Error as e: return e def ExecuteCommand(self, command): result = None try: result = MysqlStatement( command, self.connection).execute().escape().fetchall().result except AttributeError: self.logHelper.log("info", "Created mysql table.") self.ExecuteCommandWithoutFetchAndResult( "CREATE TABLE accounts ( id INT NOT NULL AUTO_INCREMENT, username TEXT NOT NULL, password TEXT NOT NULL, email TEXT NOT NULL, rank TEXT NOT NULL, loggedIn TINYINT NOT NULL DEFAULT '0', PRIMARY KEY (id))" ) return result def ExecuteCommandWithoutFetchAndResult(self, command): return MysqlStatement(command, self.connection).execute().escape().commit() def tryLogin(self, clientObject, password): #TODO: give better fedback for layer 8 if self.mysqlMode == 0: result = False lenght = None try: lenght = len( self.ExecuteCommand( "SELECT * FROM accounts WHERE username = '******'")) except: lenght = len( self.ExecuteCommand( "SELECT * FROM accounts WHERE username = '******'")) if lenght > 0: if self.ExecuteCommand( "select loggedIn,(case when loggedIn = 0 then 'loggedOut' when loggedIn = 1 then 'loggedIn' end) as loggedIn_status FROM accounts WHERE username = '******'")[0][1] != "loggedIn": if len( self.ExecuteCommand( "SELECT * FROM accounts WHERE username = '******' and password = '******'")) > 0: self.ExecuteCommandWithoutFetchAndResult( "UPDATE accounts SET loggedIn = 1 WHERE username = '******'") result = True return result else: checkLoggedIn = "select loggedIn,(case when loggedIn = 0 then 'loggedOut' when loggedIn = 1 then 'loggedIn' end) as loggedIn_status FROM accounts WHERE username = '******'" result = self.executeCommandOnLite(self.conn, checkLoggedIn) try: for row in result: if row[0] == 1: result = True else: result = False except: result = False if result == False: checkPW = "SELECT * FROM accounts WHERE username = '******' and password = '******'" result1 = self.executeCommandOnLite(self.conn, checkPW) result5 = False try: for row in result1: if (row[1] == clientObject.username): result5 = True else: result5 = False except: result5 = False if result5: updateStatus = "UPDATE accounts SET loggedIn = 1 WHERE username = '******'" self.executeCommandOnLite(self.conn, updateStatus) return result5 def logoutAccount(self, clientObject): if self.mysqlMode == 0: self.ExecuteCommandWithoutFetchAndResult( "UPDATE accounts SET loggedIn = 0 WHERE username = '******'") else: logoutAccount = "UPDATE accounts SET loggedIn = 0 WHERE username = '******'" self.executeCommandOnLite(self.conn, logoutAccount) def getAccountRank(self, clientObject): if self.mysqlMode == 0: result = self.ExecuteCommand( "SELECT rank FROM accounts WHERE username = '******'")[0][0] else: getRank = "SELECT rank FROM accounts WHERE username = '******'" result = self.executeCommandOnLite(self.conn, getRank) for row in result: print(row[0]) result = row[0] return result def updateAccountRank(self, clientObject): if self.mysqlMode == 0: self.ExecuteCommandWithoutFetchAndResult( "UPDATE accounts SET rank = '" + clientObject.rank + "' WHERE username = '******'") else: updateRank = "UPDATE accounts SET rank = '" + clientObject.rank + "' WHERE username = '******'" self.executeCommandOnLite(self.conn, updateRank)
class InputHandler: commandList = list() def importScripts(self): self.decEncHelper = DecodingEncodingHelper() self.channelManager = ChannelManager() self.clientManager = ClientManager() self.fileHelper = FileHelper() self.logHelper = LogHelper() self.mysqlHelper = MysqlHelper() def createCommand(self, name, syntax, arguments, description): command = Command(name, syntax, arguments, description) self.commandList.append(command) return command def initializeCommands(self): self.cmdListClients = self.createCommand( "listClients", "/listClients", "NONE", "Lists all connected clients with their name, ip and channel their in." ) self.cmdClear = self.createCommand("Clear", "/clear", "NONE", "Clears your interpreter console.") self.cmdHelp = self.createCommand( "Help", "/help", "NONE", "Shows a list of available commands.") self.cmdKick = self.createCommand( "Kick", "/kick <name/ip>", "<NAME/IP>", "Kicks the given IP from the server.") self.cmdBan = self.createCommand( "Ban", "/ban <name/ip> <time>", "<NAME/IP> <TIME>", "Bans the specified client for the given amount of time in minutes." ) self.cmdMonitorMode = self.createCommand("monitorMode", "/monitorMode", "NONE", "Switches to monitor mode.") self.cmdChangeRank = self.createCommand( "changeRank", "/changeRank <name/ip> <rank>", "<NAME/IP> <RANK>", "Changes the rank of the given client.") self.cmdListChannel = self.createCommand( "listChannel", "/listChannel", "NONE", "Lists all channels with their belonging clients.") self.cmdCreateChannel = self.createCommand( "createChannel", "/createChannel <name> <description> <password> <accessLevel>", "<NAME/DESCRIPTION/PASSWORD/ACCESSLEVEL>", "Creates a temporary Channel.") self.cmdRemoveChannel = self.createCommand( "removeChannel", "/removeChannel <name>", "<NAME>", "Removes the give Channel.") def __init__(self, upTime): self.upTime = upTime #Imports self.importScripts() #Create Commands self.initializeCommands() def handleInput(self, command): command = command.split() if command[0] == self.cmdClear.name: os.system('cls' if os.name == 'nt' else 'clear') elif command[0] == self.cmdListClients.name: if len(self.clientManager.clientList) < 1: self.logHelper.log("error", "No clients connected") else: self.logHelper.log("error", "Connected clients:") for clientObject in self.clientManager.clientList: self.logHelper.log( "info", clientObject.ip + " with name " + clientObject.username + " in " + clientObject.channelObject.name) elif command[0] == self.cmdHelp.name: self.logHelper.log("info", "Commands:") self.logHelper.log( "info", "----------------------------------------------------------") for command in self.commandList: self.logHelper.log( "info", command.syntax + " : " + command.description) self.logHelper.log( "info", "----------------------------------------------------------") elif command[0] == self.cmdKick.name: if len(self.clientManager.clientList) < 1: self.logHelper.log("error", "No clients connected") else: client = None try: client = command[1] except IndexError: self.logHelper.log("error", "Syntax: " + self.cmdKick.syntax) if client != None: if self.clientManager.ipExists(client): for clientObject in self.clientManager.clientList: if clientObject.ip == client: self.logHelper.log( "info", clientObject.ip + " : " + clientObject.username + " got kicked") clientObject.socketObject.sendall( self.decEncHelper.stringToBytes("402")) clientObject.socketObject.close() elif self.clientManager.usernameExists(client): for clientObject in self.clientManager.clientList: if clientObject.username.lower() == client: self.logHelper.log( "info", clientObject.ip + " : " + clientObject.username + " got kicked") clientObject.socketObject.sendall( self.decEncHelper.stringToBytes("402")) clientObject.socketObject.close() else: self.logHelper.log( "error", "Your given Ip/Name doesn't exist.") elif command[0] == self.cmdBan.name: if len(self.clientManager.clientList) < 1: self.logHelper.log("error", "No clients connected") else: client = None banTime = None try: client = command[1] banTime = int(command[2]) except IndexError: if client or banTime == None: self.logHelper.log("error", "Syntax: " + self.cmdBan.syntax) if client != None: if self.clientManager.ipExists(client): for clientObject in self.clientManager.clientList: if clientObject.ip == client: if banTime != None: if banTime == 0: self.fileHelper.addClientToBanList( clientObject.ip) self.logHelper.log( "info", clientObject.ip + " : " + clientObject.username + " got permanantly banned") clientObject.socketObject.sendall( self.decEncHelper.stringToBytes( "405" + "You got permanantly banned by the console" )) clientObject.socketObject.close() else: currentTimeStamp = datetime.datetime.now( ).timestamp() self.fileHelper.addClientToBanList( clientObject.ip + ":" + str(currentTimeStamp + int(banTime) * 60)) self.logHelper.log( "info", clientObject.ip + " : " + clientObject.username + " got banned for " + str(banTime) + "minutes") clientObject.socketObject.sendall( self.decEncHelper.stringToBytes( "405" + "You got banned for " + str(banTime) + " minutes by the console")) clientObject.socketObject.close() else: self.fileHelper.addClientToBanList( clientObject.ip) self.logHelper.log( "info", clientObject.ip + " : " + clientObject.username + " got permanantly banned") clientObject.socketObject.sendall( self.decEncHelper.stringToBytes( "405" + "You got permanantly banned by the console" )) clientObject.socketObject.close() elif self.clientManager.usernameExists(client): for clientObject in self.clientManager.clientList: if clientObject.username.lower() == client: if banTime != None: if banTime == 0: self.fileHelper.addClientToBanList( clientObject.ip) self.logHelper.log( "info", clientObject.ip + " : " + clientObject.username + " got permanantly banned") clientObject.socketObject.sendall( self.decEncHelper.stringToBytes( "405" + "You got permanantly banned by the console" )) clientObject.socketObject.close() else: currentTimeStamp = datetime.datetime.now( ).timestamp() self.fileHelper.addClientToBanList( clientObject.ip + ":" + str(currentTimeStamp + int(banTime) * 60)) self.logHelper.log( "info", clientObject.ip + " : " + clientObject.username + " got banned for " + str(banTime) + "minutes") clientObject.socketObject.sendall( self.decEncHelper.stringToBytes( "405" + "You got banned for " + str(banTime) + " minutes by the console")) clientObject.socketObject.close() else: self.fileHelper.addClientToBanList( clientObject.ip) self.logHelper.log( "info", clientObject.ip + " : " + clientObject.username + " got permanantly banned") clientObject.socketObject.sendall( self.decEncHelper.stringToBytes( "405" + "You got permanantly banned by the console" )) clientObject.socketObject.close() else: print( "[Server/Error] Your given Ip/Name doesn't exist.") elif command[0] == self.cmdListChannel.name: self.logHelper.log("info", "Channels:") self.logHelper.log( "info", "----------------------------------------------------------") for channel in self.channelManager.channelList: self.logHelper.log( "info", "-" + channel.name + " : Description:" + channel.description) self.logHelper.log("info", " Clients:") if len(channel.clientList) < 1: self.logHelper.log("info", " -channel is empty") else: for client in channel.clientList: self.logHelper.log( "info", " -" + client.ip + " : " + client.username) self.logHelper.log( "info", "----------------------------------------------------------") elif command[ 0] == self.cmdCreateChannel.name: #TODO: add things to remove user error when acces level isnst int and description contains spaces name = None description = None password = None accessLevel = None try: name = command[1] description = command[2] password = command[3] accessLevel = int(command[4]) self.channelManager.addChannel( Channel(name, description, password, accessLevel, list())) self.logHelper.log("info", "Channel " + name + " created.") except: if name or description or password or accessLevel == None: self.logHelper.log( "error", "Syntax: " + self.cmdCreateChannel.syntax) elif command[0] == self.cmdRemoveChannel.name: name = None try: name = command[1] for channel in self.channelManager.channelList: if channel.name == name: self.channelManager.removeChannel(channel) self.logHelper.log("info", "Channel " + name + " was removed.") except: if name == None: self.logHelper.log( "error", "Syntax: " + self.cmdRemoveChannel.syntax) elif command[ 0] == self.cmdChangeRank.name: #TODO: add things to remove user error for rank and check if rank isnt even a rank if len(self.clientManager.clientList) < 1: self.logHelper.log("error", "No clients connected") else: client = None rank = None try: client = command[1] rank = command[2] except IndexError: self.logHelper.log("error", "Syntax: " + self.cmdChangeRank.syntax) if client != None: if rank != None: if self.clientManager.ipExists(client): for clientObject in self.clientManager.clientList: if clientObject.ip == client: prevRank = clientObject.rank clientObject.rank = rank self.mysqlHelper.updateAccountRank( clientObject) self.logHelper.log( "info", "Changed " + clientObject.ip + ":" + str(clientObject.port) + " " + clientObject.username + " 's rank from " + prevRank + " to " + rank) elif self.clientManager.usernameExists(client): for clientObject in self.clientManager.clientList: if clientObject.username.lower() == client: prevRank = clientObject.rank clientObject.rank = rank self.mysqlHelper.updateAccountRank( clientObject) #clientObject.sendall(self.decEncHelper.stringToBytes("904" + rank))TODO: self.logHelper.log( "info", "Changed " + clientObject.ip + ":" + str(clientObject.port) + " " + clientObject.username + " 's rank from " + prevRank + " to " + rank) else: self.logHelper.log( "error", "Your given Ip/Name doesn't exist.") elif command[0] == self.cmdMonitorMode.name: monitor = True config = self.fileHelper.getConfig("Server Config") ip = config.ip + ":" + str(config.port) if len(ip) != 20: ip = " " * (20 - len(ip)) + ip while monitor: clearCount = 0 connectedClients = str(len(self.clientManager.clientList)) connectedAdmins = str(len(self.clientManager.getAdmins())) if len(connectedClients) != 3: connectedClients = "0" * ( 3 - len(connectedClients)) + connectedClients if len(connectedAdmins) != 3: connectedAdmins = "0" * ( 3 - len(connectedAdmins)) + connectedAdmins os.system('cls' if os.name == 'nt' else 'clear') try: print( "##############Monitoring##############\n#Server Ip/Port: " + ip + "#\n#Uptime: " + time.strftime( '%H:%M:%S', time.gmtime(int(time.time() - self.upTime))) + "#\n#Connected Clients: " + connectedClients + "#\n#Connected Admins: " + connectedAdmins + "#\n##############Monitoring##############") while clearCount != 5: sys.stdout.write("\x1b[1A") sys.stdout.write("\x1b[2K") clearCount = clearCount + 1 time.sleep(0.5) except KeyboardInterrupt: monitor = False os.system('cls' if os.name == 'nt' else 'clear') self.logHelper.log("info", "Exited monitor mode.") else: self.logHelper.log("error", "Unknown command: " + command[0]) self.logHelper.log("error", "type /help for a list of commands")
class Server(): inptHandler = None logHelper = None server = None ip = "" #config t = FileHelper().getConfig()[2] port = int(t[5:]) #helper def BytesToString(self, bytes): return str(bytes, "utf-8") def StringToBytes(self, string): return bytes(string, "utf-8") def __init__(self): self.inptHandler = InputHandler() self.logHelper = LoggingHelper() self.ip = str(socket.gethostbyname(socket.gethostname())) self.server = ServerThread((self.ip, self.port), RequestHandler) serverThread = threading.Thread(target=self.server.serve_forever) serverThread.daemon = True serverThread.start() self.logHelper.printAndWriteServerLog("[Server/Info] Started on ip: " + str(self.ip) + " with port: " + str(self.port) + " in " + serverThread.name) self.askForInput() def askForInput(self): while True: try: message = input() except KeyboardInterrupt: self.logHelper.printAndWriteServerLog( "[Server/Info] Gracefully stopping server...") from utils.RequestHandler import Clients #pylint: disable=E0611 if len(Clients().clientList) < 1: self.logHelper.printAndWriteServerLog( "[Server/Info] Gracefully stopped server") break else: for client in Clients().clientList: for key in client.keys(): key.sendall( self.StringToBytes( "403" + "[Client/Info] Server shut down")) self.logHelper.printAndWriteServerLog( "[Server/Info] Gracefully stopped server") break if str(message).startswith("/"): self.inptHandler.handleInput(str(message[1:])) else: self.logHelper.printAndWriteServerLog( "[Server/Error] Unknown command: (" + str(message) + ")") self.logHelper.printAndWriteServerLog( "[Server/Error] type /help for a list of commands")
def handle(self): logHelper = LoggingHelper() fileHelper = FileHelper() self.client = self.request self.clients = Clients() if self.appendClient: logHelper.printAndWriteServerLog("[Server/Info] " + str(self.client_address[0]) + ":" + str(self.client_address[1]) + " connected to the server") for clientInList in fileHelper.readTXTFile("data/", "banList"): clientInListString = clientInList.split(":") try: banTime = clientInListString[1] except IndexError: var = None #pylint: disable=W0612 if self.client_address[0] + "\n" in clientInList: logHelper.printAndWriteServerLog( "[Server/Info] " + str(self.client_address[0]) + ":" + str(self.client_address[1]) + " is permanantly banned on the server") self.client.sendall( self.StringToBytes( "405[Client/Info] You are permanantly banned on this server" )) self.client.close() self.appendClient = False elif self.client_address[ 0] + ":" + banTime in clientInList: #FIX_ME_DEPLETED:decrease banntime overtime logHelper.printAndWriteServerLog( "[Server/Info] " + str(self.client_address[0]) + ":" + str(self.client_address[1]) + " is temporary banned on the server. Remaining Time: " + clientInListString[1] + "Minutes") self.client.sendall( self.StringToBytes( "405[Client/Info] You are temporary banned on this server. Remaining Time: " + str(int(clientInListString[1])) + "Minutes")) self.client.close() self.appendClient = False else: self.clients.addClient(self.client, "None") self.appendClient = False try: self.data = self.BytesToString(self.client.recv(1024).strip()) if len(self.data[6:]) == 0: logHelper.printAndWriteServerLog("[Server/Info] " + str(self.client_address[0]) + ":" + str(self.client_address[1]) + " sent client informations") self.handleRequest(self.data) else: logHelper.printAndWriteChannelLog("[Server/Channel/Info] " + str(self.client_address[0]) + ":" + str(self.client_address[1]) + " " + self.data[3:]) self.handleRequest(self.data) except: logHelper.printAndWriteServerLog("[Server/Error] " + str(self.client_address[0]) + ":" + str(self.client_address[1]) + " closed connection unexpectedly") self.clients.removeClient(self.client, self.username)
def createCardWindowButton(self): cardCreatorThread = threading.Thread( target=CardCreatorWindow().createCardCreatorWindow( FileHelper().loadCards(), self.addCardsMode)) cardCreatorThread.daemon = True cardCreatorThread.start()