class RecieveThread(QtCore.QThread, TcpConfig): err = QtCore.pyqtSignal(str) downloadStart = QtCore.pyqtSignal(str) decryptStart = QtCore.pyqtSignal() decompressStart = QtCore.pyqtSignal() downloadComplete = QtCore.pyqtSignal() fileDownloaded = QtCore.pyqtSignal(str) fileCount = QtCore.pyqtSignal(int) update = False cur_path = str def __init__(self): super(RecieveThread, self).__init__() self.client = TcpClient() QtCore.QObject.connect(self.client, QtCore.SIGNAL("downloadStart(QString)"), self.on_download_start) QtCore.QObject.connect(self.client, QtCore.SIGNAL("decryptStart()"), self.on_decrypt_start) QtCore.QObject.connect(self.client, QtCore.SIGNAL("decompressStart()"), self.on_decompress_start) QtCore.QObject.connect(self.client, QtCore.SIGNAL("downloadComplete()"), self.on_download_complete) QtCore.QObject.connect(self.client, QtCore.SIGNAL("fileDownloaded(QString)"), self.on_file_downloaded) QtCore.QObject.connect(self.client, QtCore.SIGNAL("fileCount(int)"), self.on_file_count) def set_configs(self, tcpserver, tcpport, usr, pwd, update, path): self.TCPServer = tcpserver self.TCPPort = tcpport self.user = usr self.passwd = pwd self.update = update self.cur_path = path def on_file_downloaded(self, fname): self.fileDownloaded.emit(fname) def on_download_start(self, fname): self.downloadStart.emit(fname) def on_decrypt_start(self): self.decryptStart.emit() def on_decompress_start(self): self.decompressStart.emit() def on_download_complete(self): self.downloadComplete.emit() def on_file_count(self, cnt): self.fileCount.emit(cnt) def run(self): if self.client.connect(self.TCPServer, self.TCPPort, self.user, self.passwd): self.client.get_files(self.update, self.cur_path) self.client.close()
def on_delete_news(self): news = {} news["header"] = self.mainWnd.newsCurWnd.ui.leTitle.text() news["date"] = self.mainWnd.newsCurWnd.ui.lbTime.text().split(">")[5].split("<")[0] news["user"] = self.mainWnd.user self.newsTmr.stop() self.del_news.set_news(news) self.del_news.start() client = TcpClient() client.connect(self.mainWnd.TCPServer, self.mainWnd.TCPPort, self.mainWnd.user, self.mainWnd.passwd) client.delete_news(self.mainWnd.newsCurWnd.ui.leTitle.text()) client.close()
class RecieveMsgThread(QtCore.QThread, TcpConfig): msgRecieved = QtCore.pyqtSignal([str, str, str]) msgNone = QtCore.pyqtSignal() def __init__(self): super(RecieveMsgThread, self).__init__() self.client = TcpClient() def set_configs(self, tcpserver, tcpport, usr, pwd): self.TCPServer = tcpserver self.TCPPort = tcpport self.user = usr self.passwd = pwd def run(self): if self.client.connect(self.TCPServer, self.TCPPort, self.user, self.passwd): msg = self.client.get_messages() if msg == "[EMPTY-MSG]": self.client.close() self.msgNone.emit() else: self.msgRecieved.emit(msg["FromUser"], msg["Time"], msg["Data"]) self.client.close()
class SendFilesThread(QtCore.QThread): connectionStart = QtCore.pyqtSignal() err = QtCore.pyqtSignal(str) compressStart = QtCore.pyqtSignal(str) cryptStart = QtCore.pyqtSignal(str) sendStart = QtCore.pyqtSignal(str) sendComplete = QtCore.pyqtSignal() sendFileComplete = QtCore.pyqtSignal() def __init__(self): super(SendFilesThread, self).__init__() self.cfg = Configs() self.app_path = AppPath().main() self.a_key = AES256_cert_read("".join((self.app_path, "transf.crt"))) def send(self, wnd, TCPServer, TCPPort, flist, toUsr): """ Set connection configs """ self._wnd = wnd self._server = TCPServer self._port = TCPPort self.fileList = flist self._toUsr = toUsr def run(self): toUser = str("") self.client = TcpClient() mdb = MariaDB() if not mdb.connect(self._wnd.MDBServer, self._wnd.MDBUser, self._wnd.MDBPasswd, self._wnd.MDBBase): self.err.emit('Ошибка соединения с Базой Данных!') return toUser = mdb.get_user_by_alias(self._toUsr) mdb.close() if not os.path.exists("".join((self._wnd.app_path, "sendfiles"))): os.makedirs("".join((self._wnd.app_path,"sendfiles"))) self.connectionStart.emit() if not self.client.connect(self._server, self._port, self._wnd.user, self._wnd.passwd): print("fail connection") self.err.emit("Ошибка соединения с сервером!") return exts = [] try: exts = self.cfg.unzip_formats() except: Log().local("Error reading unzip formats") c_exts = [] try: c_exts = self.cfg.uncrypt_formats() except: Log().local("Error reading uncrypted formats") print("start send") self.client.begin_send_files(toUser) for sfile in self.fileList: lsf = sfile.split("/") l = len(lsf) fname = lsf[l - 1] """ Checking extension """ isCompress = True isCrypt = True tmp_fname = fname.split(".") ext = tmp_fname[len(tmp_fname) - 1].lower() for ex in exts: if ex == ext: isCompress = False break for ex in c_exts: if ex == ext: isCrypt = False break """ Rename file """ while True: try: parts = fname.split("'") fname = "" l = len(parts) i = 0 for part in parts: i += 1 if i < l: fname = fname + part + "_" else: fname = fname + part break except: break self.compressStart.emit(fname) if isCompress: if not zlib_compress_file(sfile, "".join((self._wnd.app_path, "sendfiles/", fname, ".z"))): Log().local("Error compressing send file: " + fname) print("error compressing") self.client.close() self.err.emit("Ошибка при сжатии файла") return else: print("".join((fname, " compressed"))) else: print(fname + " not compressed") shutil.copy2(sfile, "sendfiles/" + fname + ".z") if isCrypt: self.cryptStart.emit(fname) if not AES256_encode_file("".join((self._wnd.app_path, "sendfiles/", fname, ".z")), "".join((self._wnd.app_path, "sendfiles/", fname, ".bin")), self.a_key): Log().local("Error encrypting send file: " + fname) print("error crypting") self.client.close() self.err.emit("Ошибка при шифровании сообщения") else: print("".join((fname, " crypted"))) else: print(fname + " not crypt") shutil.copy2("".join((self._wnd.app_path,"sendfiles/", fname, ".z")), "".join((self._wnd.app_path,"sendfiles/", fname, ".bin"))) self.sendStart.emit(fname) self.client.send_file("".join((self._wnd.app_path, "sendfiles/", fname))) self.sendFileComplete.emit() try: os.remove("".join((self._wnd.app_path, "sendfiles/", fname, ".z"))) os.remove("".join((self._wnd.app_path, "sendfiles/", fname, ".bin"))) except: Log().local("Error filename") self.err.emit("Ошибка в имени файла!") self.client.end_send_files() self.sendComplete.emit() print("send complete") self.client.close()
def send_msg(wnd, msg, all, lUsrPwd, usr): """ Send message to remote tcp server """ answ = str toUser = str if msg == "": QtGui.QMessageBox.warning(wnd, 'Complete', 'Введите сообщение!', QtGui.QMessageBox.Yes) return if (usr == "") and (not all): """ If message sending to single user and user not selected then fail """ QtGui.QMessageBox.warning(wnd, 'Complete', 'Выберите пользователя!', QtGui.QMessageBox.Yes) return mdb = MariaDB() if not mdb.connect(wnd.MDBServer, wnd.MDBUser, wnd.MDBPasswd, wnd.MDBBase): QtGui.QMessageBox.critical(wnd, 'Ошибка', 'Ошибка соединения с Базой Данных!', QtGui.QMessageBox.Yes) return if not all: toUser = mdb.get_user_by_alias(usr) mdb.close() client = TcpClient() if not client.connect(wnd.TCPServer, wnd.TCPPort, wnd.user, lUsrPwd): QtGui.QMessageBox.critical(wnd, "Ошибка", "Ошибка соединения с сервером!", QtGui.QMessageBox.Yes) return if not all: answ = client.send_message(toUser, msg) else: answ = client.send_message("$ALL_USERS$", msg) client.close() if answ == "[FAIL]": QtGui.QMessageBox.critical(wnd, 'Ошибка', 'Ошибка передачи сообщения!', QtGui.QMessageBox.Yes) client.close() return if answ == "[FAIL-LEN]": QtGui.QMessageBox.critical(wnd, 'Ошибка', 'Сообщение слишком длинное!', QtGui.QMessageBox.Yes) client.close() return if answ == "[FAIL-ACCESS]": QtGui.QMessageBox.critical(wnd, 'Ошибка', 'У Вас нет прав на отправку всем пользователям!', QtGui.QMessageBox.Yes) client.close() return if answ == "[SEND-MSG-OK]": mb = MessageBase() if not all: mb.save_message(usr, msg, False) QtGui.QMessageBox.information(wnd, 'Complete', 'Сообщение отправлено!', QtGui.QMessageBox.Yes) else: mb.save_message("Всем", msg, False) QtGui.QMessageBox.information(wnd, 'Complete', 'Сообщение отправлено всем пользователям!', QtGui.QMessageBox.Yes)
class UserClient(object): def __init__(self, user_name, debug=False): self.logger = add_log('mala_%s' % user_name, debug) self.user_id = 0 self.user_name = user_name self.tcp_client = TcpClient(self) self.tcp_client.setDaemon(True) self.tcp_client.start() self.user_data = None self.action_state = 0 self.enabled_actions = ['build', 'army', 'fast_forward'] def on_message(self, message): self.logger.debug('on_message#############################') self.logger.debug(message) self.logger.debug('#######################################') if message.result == 0: func = rsp.cmd_prot_rsp_method.get(message.cmd) if func is None: rsp.default_func(self, message) return self.logger.debug('func_name: ' + func.__name__) func(self, message) else: self.logger.debug(message) def send_message(self, cmd, data): self.logger.debug('send_message: ' + cmd) self.logger.debug(data) cs_info = sp.CsInfo(**data) cs_info.cmd = getattr(sp, cmd) cs_info.id = self.user_id send_af = AppFrame() send_af.message = cs_info send_af.frame_command = cs_info.cmd send_af.frame_id = cs_info.id self.tcp_client.send(send_af) def get_action_list(self): """agent使用 获取当前可用的Action""" self.update() self.full_resource() action_list = self._get_action_list() if not [a for a in action_list if a.status == 0]: if ActionLogin(self).run(): action_list = self._get_action_list() return action_list def _get_action_list(self): action_list = [] if 'build' in self.enabled_actions: action_list += create_build_actions(self) if 'army' in self.enabled_actions: action_list += create_army_actions(self) if 'fast_forward' in self.enabled_actions: action_list += create_fast_forward_actions(self) return action_list def get_user_data(self): """agent使用 获取游戏状态信息""" return copy.deepcopy(self.user_data) def update(self): self._update_progress() def _update_progress(self): pass def login(self): self.tcp_client.open() if ActionLogin(self).run(): return True self.tcp_client.close() return False def register(self): if self.login(): ActionMove(self).run() return True return False def heart(self): def _heart(): self.send_message('ReqHeart', {'req_heart': {'revert': 1}}) t = threading.Timer(30, _heart) t.setDaemon(True) t.start() timer = threading.Timer(30, _heart) timer.setDaemon(True) timer.start() def add_cash(self, cash=1000): data = { 'req_gm': { 'gm_info': { 'gm_cmd': ['add_cash', str(cash)] } } } self.send_message('ReqGM', data) def add_resource(self, _type, num): num = str(num) if _type == 'cash': gm_cmd = ['add_cash', num] elif _type == 'energy': gm_cmd = ['add_resource', '0', num] elif _type == 'mineral': gm_cmd = ['add_resource', '1', num] elif _type == 'crystal': gm_cmd = ['add_resource', '2', num] elif _type == 'alloy': gm_cmd = ['add_resource', '3', num] else: return data = { 'req_gm': { 'gm_info': { 'gm_cmd': gm_cmd } } } self.send_message('ReqGM', data) def full_resource(self): energy_max = self.user_data['city_count']['energy_max'] mineral_max = self.user_data['city_count']['mineral_max'] energy = energy_max - self.user_data['base_info']['energy'] mineral = mineral_max - self.user_data['base_info']['mineral'] if energy > 0: self.add_resource('energy', energy) self.user_data['base_info']['energy'] = energy_max if mineral > 0: self.add_resource('mineral', mineral) self.user_data['base_info']['mineral'] = mineral_max self.logger.debug('add_resource: %s%s' % (energy, mineral)) if self.user_data['base_info']['crystal'] < 100: self.add_resource('crystal', 1000) self.user_data['base_info']['crystal'] += 1000 if self.user_data['base_info']['alloy'] < 100: self.add_resource('alloy', 1000) self.user_data['base_info']['alloy'] += 1000
def run(self): if self.task == "news": con = sqlite3.connect(self.cur_path + 'news.db') cur = con.cursor() try: cur.execute( 'CREATE TABLE news(id INTEGER PRIMARY KEY AUTOINCREMENT, title VARCHAR(512), date VARCHAR(20))') con.commit() except: pass mdb = MariaDB() if not mdb.connect(self.configs["MDBServer"], self.configs["MDBUser"], self.configs["MDBPasswd"], self.configs["MDBBase"]): self.err.emit("Ошибка соединения с Базой Данной", self.task) return news_list = mdb.check_news() l = len(news_list) if l != self.news_count: self.setNewsCount.emit(l) self.clearNews.emit() for news in news_list: cur.execute( "SELECT * FROM news WHERE title='" + news["title"] + "' and date='" + news["date"] + "'") n_list = cur.fetchall() if len(n_list) == 0: cur.execute( "INSERT INTO news(title, date) VALUES('" + news["title"] + "', '" + news["date"] + "')") con.commit() """ Show tooltip """ if not mdb.is_admin(self.user): self.showNewsBaloon.emit(news["date"], news["title"]) self.addInNews.emit(news["date"], news["title"]) mdb.close() con.close() self.checkNewsComplete.emit() self.exit(0) elif self.task == "msg_and_files": """ Checking server status (online/offline) """ client = TcpClient() if not client.check_status(self.configs["TcpServer"], self.configs["TcpPort"]): self.serverOffline.emit() else: self.serverOnline.emit() client.close() """ Checking update, messages, files """ mdb = MariaDB() if not mdb.connect(self.configs["MDBServer"], self.configs["MDBUser"], self.configs["MDBPasswd"], self.configs["MDBBase"]): self.err.emit("Ошибка соединения с Базой Данных!", self.task) return if mdb.check_update(self.user): mdb.close() print("Доступны обновления.") self.updateAvailable.emit() return if mdb.check_files(self.user): mdb.close() print("Есть новые файлы.") self.filesAvailable.emit() return if mdb.check_messages(self.user) and (not self.msg_status): mdb.close() print("Есть новые сообщения.") self.msgAvailable.emit() return mdb.close() self.nothingAvailable.emit() return