def delete_messages(): """ Delete all messages from the chatroom :param room_id: the room_id of the group """ incoming = request.get_json() Message.delete_messages_from_room_id(incoming['room_id']) return jsonify(results=incoming['room_id'])
def test_get_last_messages(self): chat = Chat.get(self.chat_id) old_message = Message.send(self.chat_id, MESSAGE, MESSAGE_TYPE) new_message = Message.send(self.chat_id, MESSAGE, MESSAGE_TYPE) got_last_messages = chat.get_last_messages(old_message.id) self.assertEqual(len(got_last_messages), 1) self.assertEqual(got_last_messages[0].get('id'), new_message.id)
def test_api_post_message(self): count = Message.query().count() response = self.app.post('/api/messages/', data=self.post, follow_redirects=True) self.assertEqual(response.status_code, 201) load = json.loads(response.data) self.assertEqual(load['message_id'], self.post['message_id']) self.assertEqual(Message.query().count(), count + 1)
def test_get_all_messages(self): second_message = Message.send(self.chat_id, MESSAGE, MESSAGE_TYPE) third_message = Message.send(self.chat_id, MESSAGE, MESSAGE_TYPE) chat = Chat.get(self.chat_id) got_messages = chat.get_last_messages() self.assertEqual(len(got_messages), 3) self.assertEqual(got_messages[1].get('id'), second_message.id) self.assertEqual(got_messages[2].get('id'), third_message.id)
def set_message(): message = Message(text_message=request.form['text'], sender=request.form['sender'], chat_room=request.form['chat_room']) message.view = False db.session.add(message) db.session.commit() return jsonify({'message': '200'})
def add_message(self): """ generates new message for tests issues :return: """ msg = Message(**self.initial) msg.put() return msg
def send_message(): """Данная функция отправляет сообщение пользователю :return: Отправилось ли сообщение """ send_message_form = SendMessageForm() chat_id = send_message_form.chat.data message = send_message_form.message.data Message.send(chat_id, message, 'usr') return dumps({"success": True, "error": ""})
def test_api_delete_message(self): msg = self.add_message() pk = msg.message_id url = '/api/messages/%s/' % pk count = Message.query().count() response = self.app.delete(url, data={}, follow_redirects=True) self.assertEqual(response.status_code, 204) key = ndb.Key('Message', pk) msg = key.get() self.assertEqual(msg, None) self.assertEqual(Message.query().count(), count - 1)
def test_put_message(self): msg = self.add_message() count = Message.query().count() url = '/api/messages/%s/' % msg.message_id response = self.app.put(url, data=self.put, follow_redirects=True) self.assertEqual(response.status_code, 200) load = json.loads(response.data) self.assertEqual(load['message_id'], self.put['message_id']) self.assertEqual(load['message_data'], self.put['message_data']) self.assertIn('created_on', load) # nothing should change self.assertEqual(Message.query().count(), count)
def test_get_last_messages(self): chat_id = Chat.create(CHAT_NAME, CHAT_CODE, CODE_TYPE) last_message = Message.send(chat_id, MESSAGE, MESSAGE_TYPE) url = MESSAGES_GET_LAST_PAGE_URL.format( chat_id=chat_id, last_message_id=last_message.id) response = self.app.get(url) self.assertEqual(response.status_code, 200)
def test_message_sending(self): message = Message.send(self.chat_id, MESSAGE, MESSAGE_TYPE) self.assertIsInstance(message, Message) self.assertEqual(message.content, MarkdownMixin.decode(MESSAGE)) self.assertEqual(message.author, USERNAME) self.assertEqual(message.chat_link, self.chat_id) self.assertEqual(message.type, MESSAGE_TYPE)
def send_message(recipient): """ Route for sending messages """ # TODO: UUsi message-luokka käytössä user = User.query.filter_by(username=recipient).first_or_404() form = MessageForm() if form.validate_on_submit(): msg = Message( author=current_user, recipient=user, body=form.message.data ) # Adds a notification of type 'unread_message_count' to # receiver, so the variable can be changed in navbar user.add_notification('unread_message_count', user.new_messages()) db.session.add(msg) db.session.commit() flash('Message sent') return redirect(url_for('main.user', username=recipient)) return render_template( '_send_message.html', title='Send Message', form=form, recipient=recipient )
def set_name(self, name): """Установка названия чата :param name: новое название чата :return: объект в разных написаниях названия чата: \ оригинальное, без тегов, экрнированные теги """ self.name = MarkdownMixin.decode(name) db.session.commit() Message.send_about_change_chat_name(self.id, MarkdownMixin.plain(self.name)) return { "original": self.name, "plain": MarkdownMixin.plain(self.name), "escaped": MarkdownMixin.escape_html(self.name) }
def route_bbs(): if request.method == 'POST': m = request.form['message'] message = Message(message=m) db.session.add(message) db.session.commit() messages = Message.query.with_entities(Message.message) return render_template('bbs.html', messages=messages)
def recieved_message(json, methods=['GET', 'POST']): """ Get received message from the socketio on the client """ json['username'] = session['username'] socketio.emit('server message', json) message = Message(user_id=session['user_id'], room_id=json["room_id"], sendTime=datetime.now(), content=json["content"]) db.session.add(message) db.session.commit()
def send_message(): """ Send a message to the chatroom. :param room_id: the room_id of the group :param content: the content of the message """ incoming = request.get_json() message = Message(user_id=session['user_id'], room_id=incoming["room_id"], sendTime=datetime.now(), content=incoming["content"]) db.session.add(message) db.session.commit() return jsonify(content=incoming["content"])
def send(chat_id, code_text, parent, message): """Отправление кода на сервер :param chat_id: Номер чата :param code_text: Код :param parent: Место в дереве коммитов :param message: Комметарий к коду :return: Сообщение о коммите и номере кода """ code_params = { "content": code_text, "message": message, "chat_link": chat_id, "parent_link": parent } code_to_send = Code(**code_params) db.session.add(code_to_send) db.session.commit() message_text = Code.SYS_MESSAGE_ADD_TEMPLATE.format( number=code_to_send.number, message=message) Message.send(chat_id, message_text, Message.SYSTEM_TYPE) if app.config['SOCKET_MODE'] == 'True': socketio.emit('commit', room=str(chat_id), broadcast=True) return code_to_send.id
def get_messages(): """ Get all the messages the chatroom has :param room_id: the room_id of the group """ incoming = request.get_json() messages = Message.get_messages_from_room_id(incoming['room_id']) messages = [{ 'user_id': message.user_id, 'sendTime': message.sendTime, 'content': message.content } for message in messages] for message in messages: user = User.get_user_with_user_id(message['user_id']) message['username'] = str(user.username) return jsonify(results=messages)
def send_message(chat_id): """ Allows a user to send a message. Takes as arguments chat_id, sender_id and content """ user_id = str(current_user.get_id()) messagetext = request.json["content"] try: newmessage = Message.from_messages(messagetext, chat_id, user_id) except KeyError as e: return jsonify(f'Missing key: {e.args[0]}'), 400 db.session.add(newmessage) db.session.commit() return jsonify(newmessage.to_messages()), 200
def send_message(recipient): user = User.query.filter_by(username=recipient).first_or_404() form = MessageForm() if form.validate_on_submit(): msg = Message(author=current_user, recipient=user, body=form.message.data) db.session.add(msg) user.add_notification('unread_message_count', user.new_messages()) db.session.commit() flash(_('Your message has been sent.')) return redirect(url_for('main.user', username=recipient)) return render_template('send_message.html', title=_('Send Message'), form=form, recipient=recipient)
def delete_message(chat_id): """ Delete a message. """ if request.json: for row in request.json: message = Message.from_messages(row, chat_id, request.args['id']) db.session.execute( ''' DELETE FROM messages WHERE message_id = :message_id ''', dict(message_id=message.message_id)) db.session.commit() return "Successfully deleted message" else: return "Error"
def message(form): form = SendMessageForm(formdata=MultiDict(form), meta={'csrf': False}) if not form.validate(): print(form.recipientID.errors + form.message.errors) # socketio.emit("sendMessageError", {"recipientEmail": form.recipientEmail.errors}) else: datetime = form.datetime.data chatID = form.chatID.data recipientID = form.recipientID.data message = form.message.data # socketio.emit("sendMessageError", {"recipientEmail": ""}) id = Message.query.count() + 1 newMessage = Message(id=id, datetime=datetime, chatID=chatID, senderID=session["user"]["id"], message=message) db.session.add(newMessage) db.session.commit() socketio.emit("sentMessage", { "chatID": chatID, "recipientID": recipientID, "senderID": session.get("user").get("id"), "message": message, "datetime": datetime }, room=session.get("user").get("id")) user = db.session.query(User).filter( (User.id == session["user"]["id"])).first() socketio.emit("receivedMessage", { "chatID": chatID, "recipientID": recipientID, "senderID": session.get("user").get("id"), "message": message, "datetime": datetime, "firstName": user.firstName }, room=recipientID)
def test_get_info_should_system_type(self): other_message = Message.send(self.chat_id, MESSAGE, MESSAGE_SYSTEM_TYPE) message_info = other_message.get_info() self.assertEqual(message_info.get('type'), MESSAGE_SYSTEM_TYPE)
def test_socket_not_emit_when_message_sending_and_app_not_in_socket(self): with patch.object(socketio, 'emit') as socketio_emit: app.config['SOCKET_MODE'] = 'False' Message.send(self.chat_id, MESSAGE, MESSAGE_TYPE) socketio_emit.assert_not_called()
def test_socket_emit_when_message_sending(self): with patch.object(socketio, 'emit') as socketio_emit: Message.send(self.chat_id, MESSAGE, MESSAGE_TYPE) socketio_emit.assert_called()
def test_chat_has_message(self): chat = Chat.get(self.chat_id) message_id = Message.send(self.chat_id, MESSAGE, 'usr').id - 1 self.assertTrue(chat.has_message(str(message_id))) self.assertFalse(chat.has_message(str(message_id + 1)))
def setUp(self): BaseTestModel.setUp(self) self.chat_id = Chat.create(CHAT_NAME, CHAT_CODE, CODE_TYPE) self.message = Message.send(self.chat_id, MESSAGE, MESSAGE_TYPE)