示例#1
0
    def newMeassge(self, type, c_name, r_name):

        # print(json.load(request.json))
        message = MessageModel()

        message.create_name = c_name
        message.recipient_name = r_name
        message.message_type = type
        message.message_satus = 0
        # if type == 0:
        #     message.message_notes = '您有一条入库申请'
        # elif type == 1:
        #     message.message_notes = '您有一条出库申请'
        # elif type == 5:
        #      message.message_notes = '您有一条入库申请通过消息'
        # elif type == 6:
        #      message.message_notes = '您有一条入库申请驳回消息'
        try:
            db.session.add(message)
            #db.session.commit()
            db.session.commit()
        except IntegrityError as e:
            print(e)
            return NotUnique.message, NotUnique.code
        except SQLAlchemyError as e:
            print(e)
            return DBError.message, DBError.code
        return Success.message, Success.code
示例#2
0
def first_message_to_user(content, email, device):
    try:
        user = db.session.query(UserModel).filter(
            UserModel.email == email).first()
        if user is None:
            raise e_account.UserNotFound
        elif not device.circle.has_member(user):
            raise e_cirle.UserNotPartOfCircle
        conversation = Conversation(device_access=True)
        conversation.circle = device.circle
        conversation.name = "NewConversation"
        link = UserToConversation(privilege="ADMIN")
        link.user = user
        link.conversation = conversation
        message = Message(content=content["text_message"]
                          if "text_message" in content else "",
                          is_user=False)
        message.conversation = conversation
        message.device = device
        media_list = []
        if "files" in content:
            for file in content["files"]:
                media = Media()
                media.identifier = file
                MessageToMedia(message=message, media=media)
                db.session.commit()
                media_list.append(media.get_simple_content())
        db.session.commit()
        sockets.notify_user(user, False, 'conversation', {
            "conversation_id": conversation.id,
            "event": 'invite'
        })
        info_and_message = "[" + conversation.name + "] " + device.name + " : " + str(
            message.text_content)
        try:
            messenger_conversation_model_send(0, conversation,
                                              info_and_message)
        except Exception:
            pass
        try:
            hangout_conversation_model_send(0, conversation, info_and_message)
        except Exception:
            pass
        response = {
            "data": {
                "success": True,
                'media_list': media_list,
                'message_id': message.id
            },
            "status_code": 200
        }
    except (e_cirle.CircleException, e_account.AccountException) as exception:
        response = {
            "data": {
                "success": False,
                "message": exception.message
            },
            "status_code": exception.status_code
        }
    return response
示例#3
0
def message_create():
    # Retrieve a particular users workhistorys

    username_of_jwt = get_jwt_identity()
    user_sender_object = User.query.get(username_of_jwt)
    user_receiver_object = User.query.get(request.json["username_of_receiver"])

    if not (user_sender_object or user_receiver_object):
        return abort(401, description="A user is invalid")

    if not request.json["content"]:
        return abort(401, description="Must have non-empty content")

    # user_id = get_jwt_identity()
    message_object_from_fields = Message()

    message_object_from_fields.username_of_sender = username_of_jwt
    message_object_from_fields.username_of_receiver = request.json[
        "username_of_receiver"]
    message_object_from_fields.content = request.json["content"]

    db.session.add(message_object_from_fields)

    db.session.commit()
    return jsonify(message_schema.dump(message_object_from_fields))
示例#4
0
def createMessage(token):
    """
    <span class="card-title">This call will create a new Message in the DB</span>
    <br>
    <b>Route Parameters</b><br>
        - seToken: 'seToken'
    <br>
    <br>
    <b>Payload</b><br>
     - JSON Object, Example: <br>
    {<br>
        'groupId' : 123456789,<br>
        'message' : 'Class is canceled',<br>
        'isProject' : true<br>
    }<br>
    <br>
    <br>
    <b>Response</b>
    <br>
    201 - Created
    <br>
    400 - Bad Request
    <br>
    403 - Invalid token or not a lecturer
    """
    if not request.data:
        return bad_request("no data")
    # if not is_lecturer(token):  #todo: change to lecturer id
    #     return forbidden("Invalid token or not a lecturer!")

    user = get_user_by_token(token)

    #try to parse payload
    try:
        payload = json.loads(request.data)
    except Exception as e:
        return bad_request("here")

    try:
        msg = Message(groupId=payload['groupId'], message=payload['message'], msgDate=datetime.datetime.now(), master_id=user.key().id())
    except Exception as e:
        print e
        return bad_request("there")

    try:
        msg.isProject = payload['isProject']
    except Exception as e:
        pass

    db.put(msg)
    db.save
    return Response(response=msg.to_JSON(),
                            status=200,
                            mimetype="application/json")
示例#5
0
    def post(self):
        sender = username = self.get_cookie("username")
        receiver = self.request.get("receiver")
        title = self.request.get("title")
        content = self.request.get("content")

        if receiver and title and content:
            msg = Message(sender=sender, receiver=receiver, title=title, content=content)
            msg.put()
            self.redirect("/")
        else:
            self.response.out.write("Error in Messages.post()")
示例#6
0
def list_parse(args, user=None):
    if args.list and user:
        print(f" Messages list sent to user '{user.username}':")
        for message in Message.load_all_messages_for_user(user.id):
            print(f"\t{message}")
        print(f" Messages list sent from user '{user.username}':")
        for message in Message.load_all_messages_from_user(user.id):
            print(f"\t{message}")
        sys.exit()
    elif args.list and not user:
        print("All messages list")
        for message in Message.load_all_messages():
            print(f"\t{message}")
        sys.exit()
示例#7
0
    def post(self):
        sender = username = self.get_cookie("username")
        receiver = self.request.get('receiver')
        title = self.request.get('title')
        content = self.request.get('content')

        if receiver and title and content:
            msg = Message(sender=sender,
                          receiver=receiver,
                          title=title,
                          content=content)
            msg.put()
            self.redirect('/')
        else:
            self.response.out.write("Error in Messages.post()")
def store_message_in_db():

    try:
        data = request.json

        # validate post inputs
        MessageSchema().load(data)

        sender = data['sender']
        receiver = data['receiver']
        message = data['message']
        subject = data['subject']

        new_message = Message(sender=sender,
                              receiver=receiver,
                              message=message,
                              subject=subject)

        db.session.add(new_message)
        db.session.commit()

        return message_schema.dump(new_message)

    except ValidationError as err:
        return err.messages
示例#9
0
 def on_get_list(self):
     data = ContactMessage.select()
     """\
         .where(
         (ContactMessage.message_from == current_user.uuid) | (ContactMessage.message_to == current_user.uuid) & (
         ContactMessage.deleted == False))"""
     return data
示例#10
0
def before_request():
    msg = []
    msg.append("----BEGIN REQUEST----")
    msg.append("Date: %s" % (datetime.datetime.now()))
    msg.append("IP Address: %s" % (request.remote_addr))
    msg.append("Method: %s" % (request.method))
    msg.append("URL: %s" % (request.url))
    if request.args is not None and len(request.args) > 0:
        msg.append("Args: %s" % (request.args))
    if request.json is not None:
        msg.append("JSON: %s" % (request.json))
    if request.form is not None and len(request.form) > 0:
        msg.append("FORM: %s" % (request.form))
    msg.append("----END REQUEST----\n")
    log.log_debug("\n".join(msg))

    if config.get_config("environment") == "PROD":
        if "/static/" in request.url:
            pass
        else:
            if "/pre_signup" not in request.url:
                return redirect("/pre_signup")

    g.total_messages = 0
    if current_user.is_authenticated:
        usr = User.get(User.uuid == current_user.uuid)
        data = ContactMessage.get_user_messages(current_user.uuid)
        g.total_messages = len(data)
示例#11
0
    def provide_info(self, message):
        """
        This method is called by the remote user, it sends all the information that it has about the current devices
        connected
                {   "id": 112223,
                    "payload": "{\"type\": \"provide_info\",
                                "command": { "name":"fetch_all_drone_info"
                                }",
                    "sender": "communication_handler",
                    "to": "drone_handler",
                    "type": "drone"
                }
        """
        payload = message.payload
        info_command = payload["command"]
        name = info_command["name"]

        if name == "fetch_all_drone_info":
            r_list = []
            for drone in list(self.drones.keys()):
                r_list.append(drone.to_dict())
            result = json.dumps({"drones": r_list})

            new_message = Message("drone_handler", message.sender, "comms", {
                "type": "reply",
                "data": result
            })

            self.server.message_handler.handle_message(new_message)
示例#12
0
文件: User.py 项目: jce-il/SE-Hub
def get_stats(user):
    from models.Project import Project
    from models.Message import Message

    labels = ["Commits", "Open Issues Assigned", "Messages", "Unfinished Tasks"]
    data = [0, 0, 0, 0]
    for pid in user.projects_id_list:
        project = Project.get_by_id(int(pid))
        info = json.loads(project.info)
        stats = info["stats"]["micro"]
        p_data = stats["data"]
        p_series = stats["series"]
        try:
            user_index = p_series.index(user.username)
            # adding commits
            data[0] = data[0] + p_data[user_index][0]
            # adding open issues
            data[1] = data[1] + p_data[user_index][1]
        except Exception:
            pass
    messages = Message.all().filter("master_id =", user.key().id())
    for m in messages.run():
        data[2] = data[2] + 1

    # need to do tasks
    ####

    data = [data]
    return {"data": data, "labels": labels}
示例#13
0
 def send_message():
     email_from = request.form['email_from']
     email_to = request.form['email_to']
     message = request.form['message']
     msg = Message.create(message_from=email_from,
                          message_to=email_to,
                          message=message)
     return redirect("/")
示例#14
0
 def setUp(self):
     neo_config.load_config()
     neo_config.set_project_variables()
     neo = NeoAPI(neo_config)
     self.api = neo.activate_testing()
     self.user1 = db.session.query(UserModel).filter(
         UserModel.email == "*****@*****.**").first()
     if self.user1 is None:
         self.user1 = UserModel(email="*****@*****.**",
                                password="******",
                                first_name="firstname",
                                last_name="lastname",
                                birthday="1995-12-12")
     self.user2 = db.session.query(UserModel).filter(
         UserModel.email == "*****@*****.**").first()
     if self.user2 is None:
         self.user2 = UserModel(email="*****@*****.**",
                                password="******",
                                first_name="firstname",
                                last_name="lastname",
                                birthday="1111-11-11")
     self.circle = Circle(name="TestMessageCreate")
     self.linkCircle = UserToCircle(user=self.user1, circle=self.circle)
     self.linkCircle2 = UserToCircle(user=self.user2, circle=self.circle)
     self.conversation = Conversation(circle=self.circle,
                                      name="TestMessageCreate")
     self.linkConversation = UserToConversation(
         user=self.user1, conversation=self.conversation, privilege="ADMIN")
     self.linkConversation2 = UserToConversation(
         user=self.user2, conversation=self.conversation)
     self.message = Message(link=self.linkConversation,
                            conversation=self.conversation,
                            content="1")
     self.message2 = Message(link=self.linkConversation,
                             conversation=self.conversation,
                             content="2")
     self.message3 = Message(link=self.linkConversation2,
                             conversation=self.conversation,
                             content="3")
     db.session.commit()
     self.token1 = authenticate_user(self.api, self.user1, "test")
     self.token2 = authenticate_user(self.api, self.user2, "test")
     self.tokenAdmin = authenticate_user(self.api,
                                         "*****@*****.**",
                                         "PapieNeo2019")
示例#15
0
    def get_random_messages(self):
        time = datetime.now()

        for x in range(10):
            text = random_sentence(10)

            self.messages.append(Message(False, time, text, random.randint(1, 2) * 2))

            time = time + timedelta(days=random.randint(2, 30))
    def handle_utility(self, message):
        client = self.get_client_from_username(message.sender)
        seconds = int(round(time.time()))
        client.last_ping = seconds

        ping_payload = {"utility_group": "ping"}
        ping_message = Message("core", message.sender, MessageType.utility,
                               ping_payload)
        self.send_message_to_client(ping_message)
示例#17
0
def handle_conversation_payload(message_payload):
    try:
        payload = jwt.decode(message_payload, SECRET_KEY)
        try:
            print(message_payload)
            link = db.session.query(UserToConversation).filter(UserToConversation.id == payload["link_id"] and
                                                               UserToConversation.user_id == payload["user_id"]).first()
            message = Message(content=payload["message_text"])
            message.link = link
            message.conversation = link.conversation
            db.session.commit()
            return "Votre message a été envoyé avec succès"
        except Exception as e:
            return "Une erreur est survenue : " + str(e)
    except jwt.ExpiredSignatureError:
        return 'Message expiré, renvoyez le message'
    except jwt.InvalidTokenError:
        return 'Message expiré, renvoyez le message'
    def handle_ping(self, message):
        client = self.server.get_client_from_username(message.sender)
        client.update_last_ping()

        ping_payload = {"utility_group": "ping"}
        ping_message = Message("core", message.sender, MessageType.utility,
                               ping_payload)
        self.logger.debug("[handle_ping], replying ping message " +
                          str(ping_message))
        self.server.send_message_to_client(ping_message)
示例#19
0
def deleteMessage(token, msgId):
    """
    <span class="card-title">>This Call will delete a message by owner token</span>
    <br>
    <b>Route Parameters</b><br>
        - SeToken: token
        - msgId: 1234567890
    <br>
    <br>
    <b>Payload</b><br>
     - NONE
    <br>
    <br>
    <b>Response</b>
    <br>
    200 - JSON Example:<br>
    <code>
        {<br>
            'groupId' : 1234567890,<br>
            'message' : 'hello all',<br>
            'date' : {<br>
                'year': 2015,<br>
                'month': 5,<br>
                'day': 5,<br>
                'hour': 5,<br>
                'minute': 5<br>
            },<br>
            'id' : 1234567890,<br>
            'master_id' : 1234567890,<br>
            'isProject' : false<br>
        }<br>
    </code>
    <br>
    """

    user = get_user_by_token(token)
    if user is None:
        return bad_request("No such User")

    try:
        msg = Message.get_by_id(int(msgId))
    except Exception as e:
        return bad_request("Bad id format")


    if msg is None:
        return bad_request("No such Message")

    if msg.master_id != user.key().id():
        return forbidden("User is not the Creator of the message")

    db.delete(msg)
    db.save
    return no_content()
示例#20
0
def get_input():
    global server
    while True:
        s = input()
        if s == "exit":
            print(log.server_closed + get_time())
            server.close()
            os._exit(1)
            break
        elif s == "send":  # This cmd is just for test
            sid = input("session_id?")
            title = input("title?")
            content = input("content?")
            img_url = input("img_url?")
            send_to(sid, Message(title, content, img_url))
        elif s == "send2all":
            title = input("title?")
            content = input("content?")
            img_url = input("img_url?")
            send_to_all(Message(title, content, img_url))
示例#21
0
    def get(self):
        """Main rooter for deleting and displaying"""
        msg_id = re.search(r"/messages(/?)([0-9]*)", self.request.url).group(2)
        username = self.get_cookie("username")
        show, start, end, delete = self.get_params(["show", "from", "to", "delete"])

        if msg_id and delete:
            Message.delete_message(msg_id, username)
            self.redirect("/")
        elif msg_id:
            self.display_message(int(msg_id))
        else:
            if show == "received":
                self.display_inbox(username, start, end)
            elif show == "sent":
                self.display_outbox(username, start, end)
            elif show == "new":
                self.show_form_for_new_message()
            else:
                self.response.out.write("Invalid url")
示例#22
0
    def get(self):
        """Main rooter for deleting and displaying"""
        msg_id = re.search(r"/messages(/?)([0-9]*)", self.request.url).group(2)
        username = self.get_cookie("username")
        show, start, end, delete = self.get_params(
            ["show", "from", "to", "delete"])

        if msg_id and delete:
            Message.delete_message(msg_id, username)
            self.redirect("/")
        elif msg_id:
            self.display_message(int(msg_id))
        else:
            if show == "received":
                self.display_inbox(username, start, end)
            elif show == "sent":
                self.display_outbox(username, start, end)
            elif show == "new":
                self.show_form_for_new_message()
            else:
                self.response.out.write("Invalid url")
示例#23
0
    async def on_message_delete(self, message: discord.Message):
        if message.author.bot or message.type == MessageType.new_member:
            return
        if len(message.content) == 0:
            return
        member = session.query(Member) \
            .filter(Member.ServerId == message.guild.id) \
            .filter(Member.MemberId == message.author.id).first()

        saveMessage = Message(member.Id, message.channel.id, message.content)
        session.add(saveMessage)
        session.commit()
示例#24
0
def route_message(request):
    username = current_user(request)
    if request.method == 'POST':
        form = request.form()
        msg = Message.new(form)
        msg.save()
        message_list.append(msg)
    header = 'HTTP/1.1 200 F**K\r\nContent-Type: text/html\r\n'
    body = templates('html_basic.html')
    msgs = '<br/>'.join([str(m) for m in message_list])
    body = body.replace('{{messages}}', msgs)
    r = header + '\r\n' + body
    return r.encode(encoding='utf-8')
 def setUp(self):
     neo_config.load_config()
     neo_config.set_project_variables()
     neo = NeoAPI(neo_config)
     self.api = neo.activate_testing()
     self.user1 = db.session.query(UserModel).filter(
         UserModel.email == "*****@*****.**").first()
     if self.user1 is None:
         self.user1 = UserModel(email="*****@*****.**",
                                password="******",
                                first_name="firstname",
                                last_name="lastname",
                                birthday="1995-12-12")
     self.user2 = db.session.query(UserModel).filter(
         UserModel.email == "*****@*****.**").first()
     if self.user2 is None:
         self.user2 = UserModel(email="*****@*****.**",
                                password="******",
                                first_name="firstname",
                                last_name="lastname",
                                birthday="1111-11-11")
     self.circle = Circle(name="Mamie")
     self.circle2 = Circle(name="test")
     self.linkCircle = UserToCircle(user=self.user1,
                                    circle=self.circle,
                                    privilege="ADMIN")
     self.linkCircle2 = UserToCircle(user=self.user2, circle=self.circle)
     self.conversation = Conversation("test")
     self.conversation.circle = self.circle
     self.conversation.device_access = True
     self.device = Device(name="Papie")
     self.device2 = Device(name="test")
     self.device2.circle = self.circle2
     self.device2_password = self.device2.get_pre_activation_password()
     self.device2.activate(self.device2.key)
     self.device.circle = self.circle
     self.device_password = self.device.get_pre_activation_password()
     self.device.activate(self.device.key)
     self.message = Message(is_user=False)
     self.message.conversation = self.conversation
     self.message.device = self.device
     db.session.commit()
     self.token1 = authenticate_user(self.api, self.user1, "test")
     self.token2 = authenticate_user(self.api, self.user2, "test")
     self.device_token = authenticate_device(self.api, self.device,
                                             self.device_password)
     self.device2_token = authenticate_device(self.api, self.device2,
                                              self.device2_password)
     self.tokenAdmin = authenticate_user(self.api,
                                         "*****@*****.**",
                                         "PapieNeo2019")
示例#26
0
def handle_conversation_payload(message_payload):
    try:
        payload = jwt.decode(message_payload, SECRET_KEY)
        try:
            link = db.session.query(UserToConversation).filter(
                UserToConversation.id == payload["link_id"],
                UserToConversation.user_id == payload["user_id"]).first()
            user = db.session.query(User).filter(
                User.id == payload["user_id"]).first()
            if len(payload["images"]) == 0:
                message = Message(content=payload["message_text"])
                message.link = link
                message.conversation = link.conversation
                db.session.commit()
                emit('message', {
                    'conversation_id': message.conversation_id,
                    'message': message.get_simple_json_compliant_content(),
                    'time': message.sent.isoformat(),
                    'sender': user.get_simple_json_compliant_content(),
                    'media_list': [],
                    'status': 'done'
                },
                     room='conversation_' + str(message.conversation_id),
                     namespace='/')
                message.conversation.mobile_notification(
                    title="Message",
                    body=user.first_name + " vous à envoyer un message.")
            else:
                push_images_to_api(user=user,
                                   conv_id=link.conversation.id,
                                   message=payload["message_text"],
                                   attachment_images=payload["images"])
        except Exception as e:
            return "Une erreur est survenue : " + str(e)
    except jwt.ExpiredSignatureError:
        return 'Message expiré, renvoyez le message'
    except jwt.InvalidTokenError:
        return 'Message expiré, renvoyez le message'
示例#27
0
def send_message(user_from, user_to_username, msg_text):
    user_to = User.load_user_by_name(user_to_username)
    if user_to:
        message = Message()
        message.from_id = user_from.id
        message.to_id = user_to.id
        message.msg_text = msg_text
        return message.save_to_db()
    raise ValueError(f"No user '{user_to_username}' in the database.")
示例#28
0
def core_message_send(content, conversation_id, user):
    try:
        link = db.session.query(UserToConversation).filter(
            UserToConversation.conversation_id == conversation_id,
            UserToConversation.user_id == user.id).first()
        if link is None:
            raise e_conversation.ConversationNotFound
        message = Message(content=content["text_message"] if "text_message" in
                          content else "")
        message.conversation = link.conversation
        message.link = link
        media_list = []
        if "files" in content:
            for file in content["files"]:
                media = Media()
                media.identifier = file
                MessageToMedia(message=message, media=media)
                db.session.commit()
                media_list.append(media.get_simple_content())
        db.session.commit()
        response = {
            "data": {
                "success": True,
                'media_list': media_list,
                'message_id': message.id
            },
            "status_code": 200
        }
    except e_conversation.ConversationException as exception:
        response = {
            "data": {
                "success": False,
                "message": exception.message
            },
            "status_code": exception.status_code
        }
    return response
示例#29
0
    def createMessage(self, info):
        foreignID = info['foreignID']
        description = info['description'].replace('\'', '\\\'').replace('\"', '\\\"')
        # 用以区分消息类型 1 代表钱包消息, 2代表收藏消息, 3代表买家评论消息, 4代表邀请码消息
        tag = info['tag']
        # 以下三个参数只有评论消息才有, 否则为'-1'
        fromUserID = info['fromUserID']
        toUserID = info['toUserID']

        messageID = self.generateID(foreignID + description)
        message = Message(messageID=messageID, foreignID=foreignID,
                          fromUserID=fromUserID, toUserID=toUserID,
                          description=description, tag=tag)
        db.session.add(message)
        return (True, messageID)
示例#30
0
    def show_form_for_new_message(self, thread=None, id=None, friends=None):
        """Shows a form for a brand new message and a reply if given thread and id
        """
        context = {'friends': friends, 'username': self.get_cookie('username')}

        if id and thread:
            id = int(id)
            thread = int(thread)

            msg = Message.get_by_id(id)
            conv = Conversation.get_by_id(thread)

            context['receiver'] = msg.sender
            context['title'] = conv.title

        self.render("messages/new_message.html", context)
示例#31
0
    def show_form_for_new_message(self, thread=None, id=None, friends=None):
        """Shows a form for a brand new message and a reply if given thread and id
        """
        context = {'friends': friends, 'username': self.get_cookie('username')}

        if id and thread:
            id = int(id)
            thread = int(thread)

            msg = Message.get_by_id(id)
            conv = Conversation.get_by_id(thread)

            context['receiver'] = msg.sender
            context['title'] = conv.title

        self.render("messages/new_message.html", context)
    def accept_connections(self):
        """
        This method accepts connections, however this method is called by check for messages, if the own core socket
        is readable then this method is called to accept the incoming connection, later on new socket is created!
        This method accepts the connection without authenticating it.
        :return: nothing
        """
        conn, address = self.socket_layer.socket.accept()
        # If set blocking is 0 core does not wait for message and this try block fails.
        conn.setblocking(1)

        # This is a special message since it is authentication
        json_string = self.socket_layer.read_message_from_connection(
            conn).decode("utf-8")

        print("Accepting connection " + str(json_string))

        self.logger.info("Accepting connection " + str(json_string))

        # new_message = Message.json_string_to_message(json_string)
        json_package = json.loads(json_string)
        username = json_package["username"]
        password = json_package["password"]
        # TODO Check client credidentals

        # hostname = json_package["hostname"]
        # host_system_username = json_package["host_system_username"]

        if self.all_clients.get(username, None) is not None:
            self.logger.info("User reconnected in short time " + str(username))
            # This means that the client reconnected before we noticed it
            old_client = self.all_clients[username]
            self.remove_client(old_client)

        new_client = socket_client(username, password, conn)

        # we need set blocking 0 so that select works in server_controller. With this sockets will not block....
        conn.setblocking(1)
        self.all_connections.append(conn)
        # Put the newly connected client to the list
        self.all_clients[username] = new_client
        # Push a message to the queue to notify that a new client is connected
        client_connected_message = Message(username, "core", "event",
                                           "Connected")

        self.inbox_queue.put(client_connected_message)
示例#33
0
    def display_message(self, msg_id, conv_id, friends):
        username = self.get_cookie("username")
        conv = Conversation.get_by_id(conv_id)
        if username not in conv.receivers_list_norm:
            self.abort(403)
        else:
            message = Message.get_by_id(msg_id)
            if message.sender != username:
                message.read = True
            message.put()

            template_values = { 'message' : message,
                                'conv_id': conv_id,
                                'username': username,
                                'friends': friends}

            self.render("messages/display_message.html", template_values)
示例#34
0
def new_thread_message():
    sender_public_id = request.args.get('sender_public_id')
    receiver_public_id = request.args.get('receiver_public_id')
    room_id = request.args.get('room_id')

    print(sender_public_id)
    print(receiver_public_id)
    print(room_id)

    user1 = User.query.filter_by(public_id=sender_public_id).first()
    user2 = User.query.filter_by(public_id=receiver_public_id).first()

    user1_id = user1.id
    user2_id = user2.id

    print(user1_id)
    print(user2_id)
    print(room_id)

    thread = Thread.query.filter_by(user1_id=user1_id, user2_id=user2_id).first()
    if thread is None:
        thread = Thread.query.filter_by(user2_id=user1_id, user1_id=user2_id).first()

    if thread is None:
        thread = Thread(user1_id, user2_id)
        room = Room.query.filter_by(id=room_id).first()
        room.threads.append(thread)

    args_data = request.get_json()

    message_data = args_data['message']
    print(message_data)

    format_date = datetime.strptime(message_data['timestamp'], '%d/%m/%Y %H:%M')

    sender = User.query.filter_by(public_id=sender_public_id).first()

    thread.messages.append(Message(False, format_date, message_data['text'], sender.id))

    for i in thread.messages:
        print(i.to_dict())

    db.session.commit()

    return jsonify({'message': 'SUCCESS'})
示例#35
0
 def createOAMessage(self, info):
     foreignID = info['foreignID']
     description = info['description']
     # 用以区分消息类型 1 代表推送消息
     tag = info['messageTag']
     fromUserID = info['userID']
     toUserID = info['toUserID']
     messageID = self.generateID(foreignID + description)
     createTime = datetime.now()
     try:
         message = Message(messageID=messageID, foreignID=foreignID, fromUserID=fromUserID,
                           toUserID=toUserID, description=description, tag=tag,
                           createTime=createTime)
         db.session.add(message)
         db.session.commit()
         return (True, messageID)
     except Exception as e:
         print e
         errorInfo = ErrorInfo['TENDER_02']
         errorInfo['detail'] = str(e)
         db.session.rollback()
         return (False, errorInfo)
示例#36
0
    def getMessageList(self, jsonInfo):
        info = json.loads(jsonInfo)
        userID = info['userID']
        allResult = db.session.query(Message).filter(
            Message.toUserID == userID
        ).order_by(desc(Message.createTime)).all()

        messageList = [Message.generate(o=o) for o in allResult]
        try:
            count = db.session.query(func.count(Message.messageID)).filter(
                Message.toUserID == userID
            ).first()
        except Exception as e:
            print str(e)
            # traceback.print_stack()
            db.session.rollback()
            errorInfo = ErrorInfo['TENDER_02']
            errorInfo['detail'] = str(e)
            return (False, errorInfo)
        result = {}
        result['messageList'] = messageList
        result['count'] = count[0]

        return (True, result)
示例#37
0
    def test_missing_message_raise_validation_error(self):

        with self.assertRaises(ValidationError):
            message = Message()
            message.validate()
示例#38
0
 def display_message(self, msg_id):
     message = Message.get_by_id(msg_id)
     template_values = {"message": message}
     self.render("display_message.html", template_values)
示例#39
0
 def display_inbox(self, username, start, end):
     messages = Message.received(username, start, end)
     template_values = {"messages": messages}
     self.render("display_inbox.html", template_values)
示例#40
0
 def display_outbox(self, username, start, end):
     messages = Message.sent(username, start, end)
     template_values = {"messages": messages}
     self.render("display_outbox.html", template_values)
示例#41
0
def captureMessage(a=None, b=None, c=None):
    '''
        Capture JSON messages between server and client
    '''
    Msg = Message(source=a, destination=b, content=c)
    Msg.put()
示例#42
0
def getAllUserMessages(token):
    """
    <span class="card-title">>This Call will return an array of all messages (sorted by date),<br>
                                </span>
    <br>
    <b>Route Parameters</b><br>
        - SeToken: token <br>
        - groupId: 1234567890
    <br>
    <br>
    <b>Payload</b><br>
     - NONE
    <br>
    <br>
    <b>Response</b>
    <br>
    200 - JSON Example:<br>
    <code>[<br>
        {<br>
            'groupId' : 1234567890,<br>
            'message' : 'hello all',<br>
            'date' : {<br>
                'year': 2015,<br>
                'month': 5,<br>
                'day': 5,<br>
                'hour': 5,<br>
                'minute': 5<br>
            },<br>
            'id' : 1234567890,<br>
            'master_id' : 1234567890,<br>
            'isProject' : false,<br>
            'user': {<br>
        'username': '******',<br>
        'name': 'Darth Vader',<br>
        'email': '[email protected],<br>
        'isLecturer': 'True',<br>
        'seToken': 'xxxxxx-xxxxx-xxxxx-xxxxxx',<br>
        'avatar_url': 'http://location.git.com/somthing'<br>
        'isFirstLogin': False,<br>
        'campuses_id_list': [43243532532,5325325325,532532342],<br>
        'courses_id_list': [53523,43432423,432432432432]<br>
        'id': 1234567890 <br>
        },<br>
        'group': {The Group Object Project OR Campus (according to isProject)}<br><br>

        }<br>
        ]<br>
    </code>
    <br>
    """
    user = get_user_by_token(token)
    if user is None:
        return bad_request("No such User")

    arr = []

    allMsgs = Message.all()
    projectMsgs = copy.deepcopy(allMsgs)

    projectMsgs.filter('isProject =', False)
    for m in projectMsgs.run():
        if str(m.groupId) in user.courses_id_list:
            msgDic = dict(json.loads(m.to_JSON()))
            #add a key 'forSortDate' for sorting dates
            msgTime = datetime.datetime(msgDic['date']['year'], msgDic['date']['month'], msgDic['date']['day'], msgDic['date']['hour'], msgDic['date']['minute'])
            msgDic['forSortDate'] = msgTime
            arr.append(msgDic)


    allMsgs.filter('isProject =', True)
    for m in allMsgs.run():
        if str(m.groupId) in user.projects_id_list:
            msgDic = dict(json.loads(m.to_JSON()))
            #add a key 'forSortDate' for sorting dates
            msgTime = datetime.datetime(msgDic['date']['year'], msgDic['date']['month'], msgDic['date']['day'], msgDic['date']['hour'], msgDic['date']['minute'])
            msgDic['forSortDate'] = msgTime
            arr.append(msgDic)

    arr = sorted(arr, key=itemgetter('forSortDate'), reverse=True)
    for i in arr:
        del i['forSortDate']
    print arr

    if len(arr) != 0:
        return Response(response=json.dumps(arr),
                        status=200,
                        mimetype="application/json")
    else:
        return Response(response=[],
                        status=200,
                        mimetype="application/json")