Beispiel #1
0
def test_message_auto_fill_status_field():
    data = {
        "scheduled": "2030-08-2T16:12:12Z",
        "text": "oijwqoid",
        "kind": "email",
        "user_id": 1,
    }
    result = MessageSchema().load(data)
    assert result["status"] == STATUS_MAP["scheduled"]
Beispiel #2
0
def create_view():
    json_data = request.get_json()
    if not json_data:
        return return_non_success_json(400, {'message': 'No input data provided'})

    # Validate and deserialize input
    message_schema = MessageSchema(only=('recipient_address', 'sender_address', 'subject', 'body'))
    try:
        data = message_schema.load(json_data)
    except ValidationError as err:
        return return_non_success_json(422, err.messages)

    message = Message(**data.data)
    db_session.add(message)
    db_session.flush()
    db_session.commit()

    return jsonify({'messages': 'ok'})
Beispiel #3
0
def test_message_empty_data():
    try:
        MessageSchema().load({})
    except ValidationError as exc:
        assert exc.messages == {
            "kind": ["Missing data for required field."],
            "scheduled": ["Missing data for required field."],
            "text": ["Missing data for required field."],
            "user_id": ["Missing data for required field."],
        }
Beispiel #4
0
def test_message_kind_mapping_str_to_int_on_load(kind_input, kind_output):
    data = {
        "scheduled": "2040-08-2T16:12:12Z",
        "text": "oijwqoid",
        "kind": kind_input,
        "user_id": 1,
    }
    result = MessageSchema().load(data)

    assert result["kind"] == kind_output
Beispiel #5
0
def test_message_kind_mapping_int_to_str_on_dump(kind_input, kind_output):
    data = {
        "scheduled": datetime(2040, 8, 2, 16, 12, 12),
        "text": "oijwqoid",
        "kind": kind_input,
        "status": 1,
        "user_id": 1,
    }
    result = MessageSchema().dump(data)

    assert result["kind"] == kind_output
Beispiel #6
0
def test_message_status_mapping_str_to_int_on_load(status_input,
                                                   status_output):
    data = {
        "scheduled": "2040-08-2T16:12:12Z",
        "text": "oijwqoid",
        "kind": "email",
        "status": status_input,
        "user_id": 1,
    }
    result = MessageSchema().load(data)

    assert result["status"] == status_output
Beispiel #7
0
def test_message_options_fields_invalid_options():
    data = {
        "scheduled": "2040-08-2T16:12:12Z",
        "text": "oijwqoid",
        "kind": "xxxx",
        "status": "xxxx",
        "user_id": 1,
    }
    try:
        MessageSchema().load(data)
    except ValidationError as exc:
        assert exc.messages == {
            "kind": ["Must be one of: email, sms, push, whatsapp."],
            "status": ["Must be one of: scheduled, sended."],
        }
Beispiel #8
0
def test_message_schedule_cannot_be_older_than_utcnow_or_equal_to_utcnow(
    minutes_offset, ):
    _scheduled = datetime.utcnow().replace(microsecond=0) - timedelta(
        minutes=minutes_offset)
    scheduled = _scheduled.strftime("%Y-%m-%dT%H:%M:%SZ")
    data = {
        "scheduled": scheduled,
        "text": "oijwqoid",
        "kind": "sms",
        "user_id": 1,
    }
    try:
        MessageSchema().load(data)
    except ValidationError as exc:
        assert exc.messages == {
            "scheduled": ["Cannot scheduled messages into the past"],
        }
Beispiel #9
0
def test_message_load_auto_fill_created_with_utc_and_microsecond_zero():
    data = {
        "scheduled": "2040-08-2T16:12:12Z",
        "text": "oijwqoid",
        "kind": "email",
        "status": "sended",
        "user_id": 1,
    }
    result = MessageSchema().load(data)
    expected_result = {
        "created": datetime.utcnow().replace(microsecond=0),
        "kind": 1,
        "scheduled": datetime(2040, 8, 2, 16, 12, 12),
        "status": 2,
        "text": "oijwqoid",
        "user_id": 1,
    }

    assert result == expected_result
Beispiel #10
0
from app.models import Message
from app.models import Chat
from app.messages import bp
from app.schemas import MessageSchema
from app.schemas import ChatSchema
from app.errors.errors import error_response

from flask import jsonify
from flask import request

from marshmallow import ValidationError

from sqlalchemy.exc import InvalidRequestError, ArgumentError

chat_schema = ChatSchema()
msg_schema = MessageSchema()
msgs_schema = MessageSchema(many=True)


@bp.route('/get', methods=['POST'])
def get_messages():
    chat_info = request.get_json()
    if not chat_info.get('chat'):
        return error_response(status_code=400, message="missing chat id")
    try:
        chat_id = int(chat_info.get('chat'))
    except ValueError:
        return jsonify({"errors": "chat id must be an integer"}), 400
    chat = Chat.query.get_or_404(chat_id)
    return msgs_schema.jsonify(chat.messages), 200
import json
from flask import g
from flask_socketio import emit
from app.extensions import socketio
from app.decorators.auth import socketio_jwt_required, socketio_permission_required
from app.decorators.views import socketio_handle_arguments
from app.models import TokenType, RolePermission, Reaction, MessageType
from app.schemas import GroupChatMessageSchema, PrivateChatMessageSchema, MessageSchema, ReactionSchema
from app.repositories import database_repository


@socketio.event
@socketio_jwt_required(TokenType.ACCESS_TOKEN)
@socketio_permission_required(RolePermission.WRITE_CHAT_MESSAGE)
@socketio_handle_arguments(MessageSchema())
def update_chat_message(message_data, message_schema):
    """Update the content of a chat message."""
    chat_message = database_repository.get_chat_message(
        message_data["_chat_id"], message_data["_id"],
        message_data["message_type"])
    if not chat_message:
        emit("error", json.dumps({"error": "Chat message not found"}))
    elif chat_message.user_id != g.current_user.id:
        emit("error",
             json.dumps({"error": "User is not the sender of this message"}))
    elif not g.current_user.in_room(chat_message.chat_id):
        emit("error", json.dumps({"error": "User has not joined the chat"}))
    else:
        chat_message.edit(message_data["_content"])
        database_repository.add_chat_message(chat_message)