コード例 #1
0
def handlStartConversation(data):

    try:
        USER_ONE = User(userId=data['userOne']['id'],
                        name=data['userOne']['name'],
                        avatar=data['userOne']['avatar']).save()
    except (NotUniqueError, DuplicateKeyError):
        # print("user one exist in db")
        USER_ONE = User.objects.get(userId=data['userOne']['id'])
    try:
        USER_TWO = User(userId=data['userTwo']['id'],
                        name=data['userTwo']['name'],
                        avatar=data['userTwo']['avatar']).save()
    except (NotUniqueError, DuplicateKeyError):
        # print("user two exist in db")
        USER_TWO = User.objects.get(userId=data['userTwo']['id'])

        # try to create new conversation.
    try:
        # create the conversation.
        conversation = Conversation(userOne=USER_ONE, userTwo=USER_TWO)
        conversation.save()

        # add conversation reference to userOne
        USER_ONE.addConversation(conversation.pk)
        # add conversation reference to userTwo
        USER_TWO.addConversation(conversation.pk)

        # convert the conversation to Python Dictionary.
        conversation = json.loads(conversation.to_json())

        # join conversation
        join_room(str(conversation['conversationId']))
        print('join new conversationId ', str(conversation['conversationId']))
        # send the conversationId and the messages array
        emit("conversationOpen", {
            "conversationId": conversation['conversationId'],
            "messages": conversation['messages'],
            "unreadMesaages": 0
        },
             room=conversation['conversationId'])

    # if the conversation already exist.
    except (NotUniqueError, DuplicateKeyError):
        # get the old conversationId
        oldConversationId = GetConversationId(data['userOne']['id'],
                                              data['userTwo']['id'])

        # print("they are already In Conversation " + oldConversationId)
        # join the old conversation
        join_room(oldConversationId)

        print("join oldConversationId ", oldConversationId)

        # getMessages will return the messages with user(sender) details _id, name and avatart.
        messages = Conversation.objects(
            conversationId=oldConversationId).first().getMessages()

        # convert the old conversation to Python Dictionary.
        conversation = json.loads(
            Conversation.objects.get(
                conversationId=oldConversationId).to_json())
        conversation['messages'].reverse()
        # send the conversationId and the old messages array
        emit("conversationOpen", {
            "conversationId": conversation['conversationId'],
            "messages": messages['messages'],
            "unreadMesaages": messages['unreadMesaages']
        },
             room=oldConversationId)

    except Exception as e:
        print("Something want wrong: ", e)