def get(self): context = {"messages": []} for error in self.session.get_flashes("error_messages"): context["messages"].append(Message("danger", error[0])) for error in self.session.get_flashes("success_messages"): context["messages"].append(Message("success", error[0])) self.response.write(get_template('index.html').render(context))
def login(): msg = request.args.get('msg', False) if msg: msg = Message(msg, 'success') # redirect athenticated users if current_user.is_authenticated: return redirect(url_for('listOpenEvents')) # serve login page for GET request if request.method == 'GET': return render_template('login.html', msg=msg) # handle login for POST Request # ignore invalid request if not ('email' in request.form and 'password' in request.form): # bad request abort(400) user, msg_str = ems.login(request.form['email'], request.form['password']) if user: login_user(user) next = request.args.get('next') if not is_safe_url(next): return abort(400) return redirect(next or url_for('listOpenEvents')) else: msg = Message(msg_str, 'danger') return render_template('login.html', form=request.form, msg=msg)
def register(self): '''init connection and login a exist user''' if not isinstance(self.conn, socket.socket): return False, 'Not Connected to server'.title() conn = self.conn msg = Message(kind=kind_register, sender=self.username, receiver='') try: conn.sendall(msg.inBytes) except socket.error: print( '{}, RegisterError, can not send RegisterReq to server'.format( localtime())) return False, 'RegisterError, can not send RegisterReq to server' data = conn.recv(1024) try: msg = Message.ParseBytes(data) except: print('{}, RegisterError, failed to parse server response'.format( localtime())) return False, 'RegisterError, failed to parse server response' print(msg) if msg.kind == kind_register and msg.token and isinstance( msg.token, str) and msg.info == 'ok': print('{}, RegisterAndLoginSuccess, token is {}'.format( localtime(), msg.token)) self.token = msg.token self.online = True self.conn = conn, 'RegisterAndLoginSuccess' return True self.conn = None self.token = None conn.close() return False, 'Register Failed'
def start(self): Message.out("Started !") # Run thread [ service.__start__() for service in self.services if not service.is_alive() ] Message.out("Running ...")
def show_balance(self): m = Message(group=self.group_id) for player in self.players: m.appendAt(player.qq_id) m.appendPlain( f":{player.balance}00万美金,威胁卡数量:{player.intimidation}\n") m.strip() m.send()
def do(self): # TODO DB registration con = sqlite3.connect('smart4l.db') cur = con.cursor() cur.execute( 'insert into smart4l(date, data) values(?,?)', [str(time.time()), json.dumps(self.app.data)]) cur.close() con.commit() con.close() Message.out("DB registration")
def __init__(self): # TODO implement message Queue Message.out("Started !") self.socket = None self.persistent = None self.httpApi = None self.websocket = None self.data = {} self.services = [] Message.out("Running ...")
def do(self): # TODO DB registration self.con = sqlite3.connect('smart4l.db') cur = self.con.cursor() cur.execute( 'insert into smart4l(date, data) values(?,?)', [str(time.time()), json.dumps(app.lastMeasure)]) cur.close() self.con.commit() self.con.close() # TODO Close connection here too Message.out("DB registration")
def send(self): myself = Subscriber() myself.port = DEFAULT_PORT myself.ip = 'localhost' myself.id = 'sender' message = Message() message.type = 'subscription' message.senderID = 'sender' message.receiverID = 'receiver' message.body = myself self.netWriter.write('broker', message)
def send(self): myself = Subscriber() myself.port = DEFAULT_PORT # sender port myself.ip = 'localhost' myself.id = 'sender' message = Message() message.type = 'subscription' message.senderID = 'sender' message.receiverID = 'receiver' message.body = myself self.netWriter.write('broker', message) message.type = 'message' while True: text = raw_input("Enter message to send: ") if text == 'close': self.netWriter.close_socket() break recipient = raw_input('Enter receiver: ') message.body = text message.receiverID = recipient self.netWriter.write('receiver', message) return
async def process_longpoll_event(self, new_event): if not new_event: return event_id = new_event[0] if event_id != 4: evnt = LongpollEvent(self.api, event_id, new_event) return await self.process_event(evnt) data = MessageEventData() data.msg_id = new_event[1] data.attaches = new_event[6] data.time = int(new_event[4]) if 'from' in data.attaches and len(new_event) > 3: data.user_id = int(data.attaches.pop('from')) data.chat_id = int(new_event[3]) - 2000000000 data.is_multichat = True else: data.user_id = int(new_event[3]) data.is_multichat = False # https://vk.com/dev/using_longpoll_2 flags = parse_msg_flags(new_event[2]) if flags['outbox']: if not self.settings.READ_OUT: return data.is_out = True data.full_text = new_event[5].replace('<br>', '\n') if "fwd" in data.attaches: data.forwarded = MessageEventData.\ parse_brief_forwarded_messages_from_lp(data.attaches.pop("fwd")) else: data.forwarded = [] msg = Message(self.api, data) if await self.check_event(data.user_id, data.chat_id, data.attaches): msg.is_event = True await self.process_message(msg)
async def callback_processor(self, request): try: data = await request.json() if "type" not in data or "object" not in data: raise ValueError("Damaged data received.") except (UnicodeDecodeError, ValueError): return web.Response(text="ok") data_type = data["type"] if data_type == "confirmation": return web.Response(text=self.settings.CONF_CODE) obj = data["object"] if "user_id" in obj: obj['user_id'] = int(obj['user_id']) if data_type == 'message_new': await self.process_message( Message(self.api, MessageEventData.from_message_body(obj))) else: await self.process_event(CallbackEvent(self.api, data_type, obj)) return web.Response(text="ok")
def postEvent(eventType): # see if given type is valid classname = eventType.capitalize() if not classname in Event.ALL_CATEGORY: abort(400) # serve corresponding post page for given type of event if request.method == 'GET': return render_template('post_{}.html'.format(eventType.lower()), name=current_user.name) if request.method == 'POST': try: # instantiate a new obj of class of given classname eventData = Parser.ALL_DATA[classname].parseViewToModel( request.form.to_dict()) # post event and retrieve the returned eid for the new event eid = current_user.postEvent(ems, classname, eventData) except (PostEventException, EventException) as err: msg = Message(str(err), 'danger') return render_template('post_{}.html'.format(eventType.lower()), msg=msg, name=current_user.name, form=json.dumps(request.form)) return redirect(url_for('eventDetails', eid=eid))
def __send_data(self, conn, info, kind, token='', sender=None): '''服务器发送信息给用户''' message = Message(kind=kind, sender=server_name if sender is None else sender, receiver='', info=info, token=token) try: conn.sendall(message.inBytes) return True except: return False
def __send_data_close(self, conn, info): '''服务器发送警告消息后关闭连接''' message = Message(kind="server_will_close", sender=server_name, receiver='', info=info) try: conn.sendall(message.inBytes) except: pass finally: conn.close()
def try_end_game(self): m = Message(group=self.group_id) max_player = None max_value = 0 for player in self.players: if self.loot_index == 8 or player.balance >= 20: if player.balance > max_value: max_player = player max_value = max_value if max_player is not None: self.reset() self.status = Game.Status.Pending m.appendPlain("游戏结束!玩家") m.appendAt(max_player.qq_id) m.appendPlain("胜利!\n如果需要再次开始游戏,请输入.md start") m.send() return True return False
def emotion(self, receiver='', info=''): '''student send emotion, teacher reply to emotion''' msg = Message(kind=kind_emotion, sender=self.username, receiver=receiver, info=info, token=self.token) print('emotion', msg) self.q.put_nowait((1, msg)) return True
def edit_rule(self, records, _addr=None): self._reset_state() self.rule = self.get_rule_from_records(records) if self.rule.operator.type not in Config.RulesTypes: Message.ok( QC.translate("rules", "<b>Rule not supported</b>"), QC.translate( "rules", "This type of rule ({0}) is not supported by version {1}". format(self.rule.operator.type, version)), QtWidgets.QMessageBox.Warning) self.hide() return self._old_rule_name = records.value(2) self._load_rule(addr=_addr, rule=self.rule) self.show()
def get_all_users(self): if not self.online: return False msg = Message( kind=kind_get_all_users, sender=self.username, receiver='', ) self.q.put_nowait((2, msg)) return True
def p2p_chat(self, receiver, info): '''chat one to one''' if not self.online: return False msg = Message(kind=kind_p2p_chat, sender=self.username, receiver=receiver, info=info, token=self.token) self.q.put_nowait((1, msg)) return True
def broadcast(self, info): '''广播消息''' message = Message(kind='BroadCasting', sender=server_name, receiver='', info=info) for conn in conn_user_map: try: receiver = conn_user_map[conn] conn.sendall(message.inBytes) except: if 'receiver' in locals(): receiver = locals()['receiver'] self.logout(user_name=receiver.username)
def p2p_chat(self, sender, receiver, info, kind='p2p_chat'): '''点对点聊天''' if self.check_user(receiver) != usr_online: return False receiver = users[receiver] conn = receiver.conn message = Message(kind=kind, sender=sender, receiver='', info=info) try: conn.sendall(message.inBytes) return True except: self.logout(receiver) return False
def login(self): if not isinstance(self.conn, socket.socket): return False, 'Not Connected to server'.title() conn = self.conn # send to server username msg = Message(kind=kind_login, sender=self.username, receiver='') try: conn.sendall(msg.inBytes) except socket.error: print('{}, LoginError, can not send LoginReq to server'.format( localtime())) return False, 'LoginError, can not send LoginReq to server' # receive server response to login req data = conn.recv(1024) # print('receive server response to login req', data) try: msg = Message.ParseBytes(data) except: print('{}, LoginError, failed to parse server response'.format( localtime())) print(str(data, encoding='utf-8')) return False, 'LoginError, failed to parse server response' print(msg) if msg.kind in [kind_login, kind_register] and msg.token and isinstance( msg.token, str) and msg.info == 'ok': print('{}, LoginSuccess, token is {}'.format( localtime(), msg.token)) self.token = msg.token self.online = True self.conn = conn return True, 'LoginSuccess' self.conn = None self.token = None conn.close() return False, msg.info
def _save_db_config(self): dbtype = self.comboDBType.currentIndex() self._cfg.setSettings(Config.DEFAULT_DB_TYPE_KEY, dbtype) if dbtype == self._db.get_db_file(): return if self.comboDBType.currentIndex() != Database.DB_TYPE_MEMORY: if self.dbLabel.text() != "": self._cfg.setSettings(Config.DEFAULT_DB_FILE_KEY, self.dbLabel.text()) else: Message.ok( QC.translate("preferences", "Warning"), QC.translate( "preferences", "You must select a file for the database<br>or choose \"In memory\" type." ), QtWidgets.QMessageBox.Warning) return Message.ok( QC.translate("preferences", "DB type changed"), QC.translate("preferences", "Restart the GUI in order effects to take effect"), QtWidgets.QMessageBox.Warning)
def signup(): # serve page on GET request if request.method == 'GET': return render_template('signup.html') # handle registration form try: userData = UserData.parseViewToModel(request.form) newGuest = Guest(userData) ems.addUser(newGuest) except Exception as err: msg = Message(str(err), 'danger') return render_template('signup.html', msg=msg, form=json.dumps(request.form)) return redirect(url_for('login', msg='Successfully signed up'))
def heart_beat(self): '''send heart beat package every 5 s''' while self.flag: if self.conn is None: print('{}, NoConnection, heartbeat skip.'.format(localtime())) continue if self.token is None: print('{}, NoToken, heartbeat skip.'.format(localtime())) msg = Message(kind=kind_heartbeat, sender=self.username, receiver='', token=self.token) try: self.q.put_nowait((8, msg)) except socket.error: self.online = False time.sleep(5)
def re_login_with_token(self): if self.online is False and self.token: if self.conn is not None: self.init_connect() conn = self.conn msg = Message(kind=kind_relogin, sender=self.username, receiver='', token=self.token) try: conn.sendall(msg.inBytes) except socket.error: print('{}, ReLoginError, can not send ReLoginReq to server'. format(localtime())) return False self.conn = conn return True return False
def init_connect(self): conn = socket.socket() try: conn.connect((host, port), ) except socket.error: print('{}, ConnectionError, can not connect to server'.format( localtime())) return False, 'ConnectionError, can not connect to server' data = conn.recv(1024) try: msg = Message.ParseBytes(data) except: print('{}, RegisterError, failed to parse server response'.format( localtime())) return False, 'RegisterError, failed to parse server response' print(msg) self.conn = conn return True, 'Connected'
def send(self): myself = Subscriber() myself.port = DEFAULT_PORT myself.ip = 'localhost' myself.id = 'app2' message = Message() message.type = 'subscription' message.senderID = 'app2' message.receiverID = 'broker' message.body = myself self.netWriter.write('broker', message)
def send(self): myself = Subscriber() myself.port = DEFAULT_PORT # sender port myself.ip = 'localhost' myself.id = 'app1' message = Message() message.type = 'subscription' message.senderID = 'app1' message.receiverID = 'broker' message.body = myself self.netWriter.write('broker', message) message.type = 'message' tree = ET.parse('country_data.xml') root = tree.getroot() recipient = 'app2' message.body = open('country_data.xml').read() message.receiverID = recipient self.netWriter.write('app2', message)
def __method(self, name, args, kwargs): rpc_socket = self.__init_socket() message = Message(rpc_socket, self.__recv_timeout, self.__send_timeout) smsg = {'func': name, 'args': args, 'kwargs': kwargs} message.send(smsg) try: rmsg = message.recv() finally: message.close_socket() if isinstance(rmsg, BaseException): raise rmsg else: return rmsg
def receive(self): while self.flag: if self.token is None or self.conn is None: continue try: data = self.conn.recv(1024) except socket.error: continue try: msg = Message.ParseBytes(data) except (TypeError, ValueError): continue if msg.kind == kind_relogin and msg.info == info_ok: print('{}, ReLogin success!'.format(localtime())) self.online = True if msg.kind == kind_heartbeat and msg.info == info_ok: print('{}, HeartBeat from server'.format(localtime())) if msg.kind == kind_get_all_users: self.friends.update(msg.info) if msg.kind == kind_emotion: self.store_new_messages(msg)
def _show_message(self, text): Message.ok(text, "", QtWidgets.QMessageBox.Warning)
def fail(message): Message.fail(message) sys.exit(1)
def warning(message): Message.warning(message)
def info(message): Message.ok(message)
def ok(message): Message.ok(message)
def unknown(option, argv): Message.fail("Unknown Option: " + option) sys.exit(1)
def _save_settings(self): if self.tabWidget.currentIndex() == 0: self._cfg.setSettings(self._cfg.DEFAULT_ACTION_KEY, self.comboUIAction.currentIndex()) self._cfg.setSettings(self._cfg.DEFAULT_DURATION_KEY, int(self.comboUIDuration.currentIndex())) self._cfg.setSettings(self._cfg.DEFAULT_TARGET_KEY, self.comboUITarget.currentIndex()) self._cfg.setSettings(self._cfg.DEFAULT_TIMEOUT_KEY, self.spinUITimeout.value()) self._cfg.setSettings(self.CFG_DISABLE_POPUPS, bool(self.popupsCheck.isChecked())) # this is a workaround for not display pop-ups. # see #79 for more information. if self.popupsCheck.isChecked(): self._cfg.setSettings(self._cfg.DEFAULT_TIMEOUT_KEY, 0) elif self.tabWidget.currentIndex() == 1: self._show_status_label() addr = self.comboNodes.currentText() if (self._node_needs_update or self.checkApplyToNodes.isChecked()) and addr != "": try: notif = ui_pb2.Notification(id=int( str(time.time()).replace(".", "")), type=ui_pb2.CHANGE_CONFIG, data="", rules=[]) if self.checkApplyToNodes.isChecked(): for addr in self._nodes.get_nodes(): error = self._save_node_config(notif, addr) if error != None: self._set_status_error(error) return else: error = self._save_node_config(notif, addr) if error != None: self._set_status_error(error) return except Exception as e: print(self.LOG_TAG + "exception saving config: ", e) self._set_status_error( QC.translate("preferences", "Exception saving config: {0}").format( str(e))) self._node_needs_update = False elif self.tabWidget.currentIndex() == 2: dbtype = self.comboDBType.currentIndex() self._cfg.setSettings(Config.DEFAULT_DB_TYPE_KEY, dbtype) if dbtype == self._db.get_db_file(): return if self.comboDBType.currentIndex() != Database.DB_TYPE_MEMORY: if self.dbLabel.text() != "": self._cfg.setSettings(Config.DEFAULT_DB_FILE_KEY, self.dbLabel.text()) else: Message.ok( QC.translate("preferences", "Warning"), QC.translate( "preferences", "You must select a file for the database<br>or choose \"In memory\" type." ), QtWidgets.QMessageBox.Warning) return Message.ok( QC.translate("preferences", "DB type changed"), QC.translate( "preferences", "Restart the GUI in order effects to take effect"), QtWidgets.QMessageBox.Warning)