def get_messages(message_id=None):
    if message_id is not None:
        message = Message.get(db.session, message_id)
        return jsonify(message.serialize) if message is not None else {}
    else:
        messages = Message.get(db.session)
        return jsonify([message.serialize for message in messages])
Exemplo n.º 2
0
def create_message(data):
    receiver = data['receiver']
    body = data['body']

    message = Message(receiver=receiver, body=body)
    message.save()
    return message
Exemplo n.º 3
0
def messinfo(userid=None):
    if request.method == "POST":
        userid = request.form["userid"]
        data = Message.get_unenroll(userid)
        return jsonify(data)
    data = Message.get_unenroll(userid)
    return jsonify(data)
Exemplo n.º 4
0
def home_page():
    db = Database()
    form = AddMessageForm()
    answerForm = AddAnswerForm()
    if form.validate_on_submit():
        title = form.data['title']
        text = form.data['text']
        message = Message(title, text)
        message.username = current_user.username
        db.add_message(message)
        flash('message added')
        return redirect(url_for('site.home_page'))
    if answerForm.validate_on_submit():
        text = answerForm.data['text']
        messageId = answerForm.data['messageID']
        db.add_message_answer(
            MessageAnswer(text, 0, current_user.username, messageId))
        flash('answer added')
        return redirect(url_for('site.home_page'))
    messages = db.get_messages()
    messageAnswer = db.get_message_answers()
    return render_template('home.html',
                           answers=messageAnswer,
                           answerForm=answerForm,
                           form=form,
                           messages=messages)
Exemplo n.º 5
0
def send_message(*, account: Account, id: int, type: str, content: str):
    def get_account_name():
        if account.account_type == 'user':
            u = get_user_account(account)
            return u.firstname + ' ' + u.lastname
        else:
            c = get_company_account(account)
            return c.name

    receiver = get_account_with_id(id=id)
    if receiver is None:
        return False
    check_message_type(type)
    m = Message(
        sender=account,
        receiver=receiver,
        type=type,
        content=content,
        published_date=int(time.time()),
    )
    m.save()

    device = FCMDevice.objects.filter(user=receiver)
    for d in device:
        response = d.send_message(title=get_account_name() +
                                  ' sent you a message',
                                  body=m.content,
                                  sound=True)
        # print(response)

    return True
Exemplo n.º 6
0
 def __send_text(cls, content: dict) -> Message:
     """
     Business method to send a text message.
     """
     SendTextMessageQueryValidation.validate(content)
     new_message = Message()
     new_message.text = content[cls.TEXT]
     return new_message
def create_message():
    payload = request.get_json()
    new_message = Message(channel_type=payload.get('channelType', None),
                          message_template=payload.get('message', None),
                          group_id=payload.get('groupId', None),
                          company_id=payload.get('companyId', None))
    #TODO: Add validation of request before hitting the database
    created_message = Message.add(db.session, new_message)
    return jsonify(created_message.serialize)
Exemplo n.º 8
0
 def __send_video(cls, content: dict) -> Message:
     """
     Business method to send a video message.
     """
     SendVideoMessageQueryValidation.validate(content)
     new_message = Message()
     new_message.url = content[cls.URL]
     new_message.source = content[cls.SOURCE]
     return new_message
Exemplo n.º 9
0
def addMessage():
    form = request.json
    if request.method == 'POST':
        with db.auto_commit():
            message = Message()
            message.set_attrs(form)
            db.session.add(message)

        return jsonify({'code': 0, 'message': '留言成功'})
    return jsonify({'code': 0, 'message': '操作不当'})
Exemplo n.º 10
0
 def __send_image(cls, content: dict) -> Message:
     """
     Business method to send an imagem message.
     """
     SendImageMessageQueryValidation.validate(content)
     new_message = Message()
     new_message.url = content[cls.URL]
     new_message.width = content[cls.WIDTH]
     new_message.height = content[cls.HEIGHT]
     return new_message
Exemplo n.º 11
0
    def get(self):
        msgCount = Message.objects((Q(sender_id__ne=app.config["HISHOP_UID"])
                                    & Q(receiver_id=current_user)),
                                   isRead=False).count()

        ntfCount = Message.objects((Q(sender_id=app.config["HISHOP_UID"])
                                    & Q(receiver_id=current_user)),
                                   isRead=False).count()

        return {'msgCount': msgCount, 'ntfCount': ntfCount}
Exemplo n.º 12
0
def searchMessage(terms):
    q = Q.PriorityQueue()
    messages = SlackMessage.query.all()
    terms = strip_terms(terms)
    '''
    Create a new Message object here to put in the queue
    because at the moment, it's easier to just create an object with the property
    `score`, rather than injecting score into SlackMessage model
    '''
    for message in messages:
        msg = Message(id=message.id,
                      url=message.url,
                      description=message.description,
                      message_text=message.message_text,
                      score=0,
                      tags=message.tags,
                      author=message.author,
                      annotator=message.annotator)
        text = msg.description.lower() + " " + msg.message_text.lower(
        ) + " " + msg.annotator.lower()
        tags = set()
        for tag in msg.tags:
            tags.add(tag)
        for term in terms:
            if term in text:
                msg.setScore(msg.getScore() + 1)
            for tag in tags:
                if term in tag or tag in term:
                    msg.setScore(msg.getScore() + 5)
        if msg.getScore() > 0:
            q.put(msg)
    app.logger.info(q)
    return q
Exemplo n.º 13
0
def update_message():
    payload = request.get_json()
    updated_message = Message(message_id=payload.get('messageId', None),
                              channel_type=payload.get('channelType', None),
                              message_template=payload.get('message', None),
                              group_id=payload.get('groupId', None),
                              company_id=payload.get('companyId', None),
                              active=payload.get('active', True))
    #TODO: Add validation of request before hitting the database
    updated_message = Message.update(db.session, updated_message)
    return jsonify(updated_message.serialize)
Exemplo n.º 14
0
    def sendMessage(self):
        message = self.messageBox.toPlainText()

        if not message == '':
            keys = self.api.getAllPublicKeys()
            for key in keys:
                m = Message(message,key["publicKey"])
                me = m.getFinal(key["username"])
                self.irc.sendMessage(me)
            mess = '<span style="color:green; font-weight: bolder";>' + self.username + "</span>" + " : " + message
            self.appendMessage(mess)
            self.messageBox.clear()
Exemplo n.º 15
0
    def sendMessage(self):
        message = self.messageBox.toPlainText()

        if not message == '':
            keys = self.api.getAllPublicKeys()
            for key in keys:
                m = Message(message, key["publicKey"])
                me = m.getFinal(key["username"])
                self.irc.sendMessage(me)
            mess = '<span style="color:green; font-weight: bolder";>' + self.username + "</span>" + " : " + message
            self.appendMessage(mess)
            self.messageBox.clear()
Exemplo n.º 16
0
def edit_message_page(message_id):
    if current_user.is_admin:
        form = AddMessageForm()
        db = Database()
        message = db.get_message(message_id)
        if form.validate_on_submit():
            message = Message(form.data['title'], form.data['text'])
            message.id = message_id
            db.edit_message(message)
            flash('message edited')
            return redirect(url_for('site.home_page'))
        return render_template('message.html', form=form, message=message)
    return redirect(url_for('site.home_page'))
Exemplo n.º 17
0
    def test_get_messages(self):
        message_dates = [
            '2015-12-12 12:12:12',
            '2015-11-11 11:11:11',
            '2016-01-01 01:01:01',
            '2014-04-04 04:04:04',
            '2015-11-11 12:12:12',
            '2015-11-11 10:10:10',
        ]

        # Create the messages
        for date in message_dates:
            message = Message(
                receiver='pjot',
                date_created=datetime.strptime(date, '%Y-%m-%d %H:%M:%S'),
                body='Some random body',
            )
            message.save()

        # Fetch them using API
        response = self.get_json('/api/v1/messages')
        assert response.status_code == 200

        data = json.loads(response.data)
        messages = data['messages']
        assert len(messages) == len(message_dates)

        # Check that they are sorted by date
        sorted_messages = sorted(messages,
                                 key=lambda message: message['date_created'],
                                 reverse=True)
        for m1, m2 in zip(messages, sorted_messages):
            assert m1['id'] == m2['id']

        # Fetch first 3
        response = self.get_json('/api/v1/messages?limit=3')
        assert response.status_code == 200

        data = json.loads(response.data)
        # Check that they are the first ones
        for i, message in enumerate(data['messages']):
            assert message['id'] == sorted_messages[i]['id']

        # Fetch next 3
        response = self.get_json('/api/v1/messages?limit=3&offset=3')
        assert response.status_code == 200

        data = json.loads(response.data)
        # Check that they are the next ones
        for i, message in enumerate(data['messages']):
            assert message['id'] == sorted_messages[i + 3]['id']
Exemplo n.º 18
0
def handle_message(senderID, receiverID, message):
    sender = User.objects.get(id=senderID)
    data = {
        "senderID": str(sender.id),
        "senderName": sender.name,
        "message": message
    }
    emit(receiverID, data, broadcast=True)
    if receiverID != senderID:
        emit(senderID, data, broadcast=True)
    message = Message(sender_id=senderID,
                      receiver_id=receiverID,
                      message=message)
    message.save()
Exemplo n.º 19
0
    def test_can_lookup_messages_by_story_or_group(self):
        start_message = 'start {}'.format(self.story_code.word_string)
        send_message(start_message)
        group = Group.query().get()

        answer_text = 'my answer is 42'
        status, response = send_message(answer_text)
        self.assertEqual(200, status)
        self.maxDiff = None
        self.assertIn(self.next_clue.text, response)
        expected_messages = [start_message, INTRO_INSTRUCTIONS.text, self.start_clue.text,
                             answer_text, self.next_clue.text]
        self.assertItemsEqual(expected_messages, [m.text for m in Message.for_story(self.story.uid)])
        self.assertItemsEqual(expected_messages, [m.text for m in Message.for_group(group.uid)])
Exemplo n.º 20
0
def rcv_message(msg):
    user = User.get_by_id(msg["sender_id"])
    conversation_id = msg['conversation_id']

    send({
        'msg': msg["msg"],
        'sender': user.to_dict_without_picture(),
        'conversation_id': conversation_id
    }, room=conversation_id, json=True)

    Message.add(
        msg.get("conversation_id"),
        msg.get("sender_id"),
        msg.get("msg")
    )
Exemplo n.º 21
0
def index(userid=None):
    userinfo = {"userid": userid, "messid": None}
    code = request.args.get('code')
    if code:
        source_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?'\
            +'appid={APPID}&secret={APPSECRET}&code={CODE}&grant_type=authorization_code'
        access_token_url = source_url.format(APPID=wechat_secure.appdi, APPSECRET=wechat_secure.secret, CODE=code)
        resp = requests.get(access_token_url)
        if resp.ok:
            data = eval(resp.text) # 将字符串转为字典
            openid = data['openid']
            access_token = data["access_token"]
            info_url = " https://api.weixin.qq.com/sns/userinfo?access_token={ACCESS_TOKEN}&openid={OPENID}&lang=zh_CN"
            resp_user = requests.get(info_url.format(ACCESS_TOKEN=access_token, OPENID=openid))
            if resp_user.ok:
                result = eval(resp_user.text)

                user = User.add_openid(openid=openid, headimgurl=result["headimgurl"])    # 查询数据数据不存在就储存数据
                if user:
                    userid = User.get_user_id(openid=openid)
                    messid = Message.get_messid(uid=userid)
                    userinfo["messid"] = messid
                    userinfo["userid"] = userid
        else:
            return "登录失败"
    #
    # data = Message.get_index()          # 查询数据库
    #
    # for mess, select in data:
    #     mess_dic = mess.__dict__
    #
    #     delattr(mess, "cardid")
    #
    #     setattr(mess, "images", eval(mess_dic["images"])[0])
    #     setattr(mess, "userinfo", userinfo)
    #     mess._fields.append("userinfo")
    # result = jsonify(data)
    result = []
    data = Message.get_mess_all()

    for mess in data:
        mess_dict = mess.__dict__
        setattr(mess, "images", eval(mess_dict["images"])[0])
        setattr(mess, "userinfo", userinfo)
        mess._fields.append("userinfo")
        result.append(mess.__dict__)

    return render_template("index.html", result=result)
Exemplo n.º 22
0
 def post(self):
     receiverID = request.values["receiverID"]
     messages = Message.objects(
         (Q(sender_id=current_user) & Q(receiver_id=receiverID))
         | (Q(sender_id=receiverID)
            & Q(receiver_id=current_user))).order_by("+create_time")
     return messages.to_json()
Exemplo n.º 23
0
 def test_gives_hints_if_incorrect(self):
     answers = [Answer(pattern=r'tough answer', next_clue='SOME:NEXTCLUE')]
     user = MagicMock()
     message = Message(text='this is not the correct answer')
     group_mock = Mock(clue=Mock(is_endpoint=False, hint='My Hint', answers=answers))
     result = answer(message, user, group_mock)
     self.assertEqual(['My Hint'], [r.text for r in result.messages])
Exemplo n.º 24
0
 def test_returns_expected_restarted(self):
     start_message = 'Start the story'
     clue = Clue(text=start_message)
     user = Mock()
     group_mock = Mock(clue_uid='something', clue=clue)
     result = perform_action(RESTART, Message(text='restart'), user, group_mock)
     self.assertEqual([RESTARTED.text, start_message], [m.text for m in result.messages])
Exemplo n.º 25
0
 def test_returns_expected_end_of_story(self):
     clue = Clue(text='blah', answer_uids=[])
     group_mock = Mock(clue=clue)
     group_mock.story.end_message = "END"
     user = Mock()
     result = perform_action(ANSWER, Message(text='asdf'), user, group_mock)
     self.assertEqual([group_mock.story.end_message], [m.text for m in result.messages])
Exemplo n.º 26
0
def create_conversation():
    """
    Create conversation, if already exists sends old message back.
    :return:
    """
    try:
        user_a = request.json["user_a"]
        user_b = request.json["user_b"]
    except KeyError:
        return make_json_response(status=400)
    else:
        try:
            conv = Conversation.by_user(user_a, user_b)
        except Conversation.NotFound:
            try:
                conv = Conversation.make_between(user_a, user_b)
            except User.NotFound:
                return make_json_response(status=404)
            else:
                return jsonify(
                    {
                        "conversation": conv.to_dict(),
                        "messages": []
                    }
                )
        else:
            return jsonify(
                {
                    "conversation": conv.to_dict(),
                    "messages": Message.by_conversation(conv)
                }
            )
Exemplo n.º 27
0
 def test_returns_expected_joined_group(self, group_mock):
     clue = Clue(text='clue text')
     group = Mock(uid='code', clue_uid='MYSTORY:MYCLUE', clue=clue)
     group_mock.get_by_id.return_value = group
     user = User()
     result = perform_action(JOIN_GROUP, Message(text='join code'), user, None)
     self.assertEqual([JOINED_GROUP.text, 'clue text'], [m.text for m in result.messages])
Exemplo n.º 28
0
def integral():
    userid = request.args["userid"]

    if userid:
        mess = Message.get_messid(uid=userid)

    return render_template("integral.html", userid=userid)
Exemplo n.º 29
0
def send_message(data):

    bro_id = data["bro_id"]
    bros_bro_id = data["bros_bro_id"]
    message = data["message"]
    text_message = data["text_message"]

    message_data = None
    if "message_data" in data:
        message_data = data["message_data"]

    own_chat = BroBros.query.filter_by(bro_id=bro_id, bros_bro_id=bros_bro_id).first()
    other_bro_chat = BroBros.query.filter_by(bro_id=bros_bro_id, bros_bro_id=bro_id).first()

    # We assume this won't happen
    if own_chat is None:
        return None

    bro_message = Message(
        sender_id=bro_id,
        recipient_id=bros_bro_id,
        body=message,
        text_message=text_message,
        timestamp=datetime.utcnow(),
        info=False,
        data=message_data
    )

    if other_bro_chat is not None and not other_bro_chat.is_blocked():
        send_notification(data)
        # The other bro now gets an extra unread message
        if not other_bro_chat.is_removed() and not other_bro_chat.is_blocked():
            other_bro_chat.update_unread_messages()
        other_bro_chat.update_last_activity()
        other_bro_chat.check_mute()
        db.session.add(other_bro_chat)

        # We only have to update the other bro's chat.
        room_bro_2 = "room_%s" % bros_bro_id
        emit("message_event_chat_changed", other_bro_chat.serialize, room=room_bro_2)

    # We update the activity on our own chat object as well
    own_chat.update_last_activity()
    # We send the message so we've obviously read it as well.
    # own_chat.update_last_message_read_time_bro()

    own_chat.check_mute()
    db.session.add(own_chat)
    db.session.add(bro_message)
    db.session.commit()

    # We do it after saving so the message will have it's id.
    if other_bro_chat is not None and not other_bro_chat.is_blocked():
        room = get_a_room_you_two(bro_id, bros_bro_id)
        emit("message_event_send", bro_message.serialize, room=room)
    else:
        # If the user is blocked or reported we don't want to send an update to the other bro.
        own_room = "room_%s" % bro_id
        emit("message_event_send", bro_message.serialize, room=own_room)
Exemplo n.º 30
0
def insert_message(user_id, room_id, content, type):
    message = Message(user_id=user_id,
                      room_id=room_id,
                      content=content,
                      type=type)

    session.add(message)
    session.commit()
Exemplo n.º 31
0
def personal_details():
    uid = request.args["uid"]
    if uid:
        result = Message.get_unenroll(uid=uid)

        delattr(result[0], "cardid")  # 删除属性

        return jsonify(result)
Exemplo n.º 32
0
    def update(self, buffer):

        if "PRIVMSG" in buffer:

            content_message = Message.rawParse(buffer)
            decoded = Message.decode(content_message["message"])

            if "to" in decoded and decoded["to"] == self.username:
                decoded_buffer = Message.rawParse(buffer)
                message = Message.decrypt(decoded_buffer["message"],self.keys["private"])
                buffer = decoded_buffer["username"] + " : " + message.getPlainText()
                t = threading.Thread(target=self.appendMessage, args=(buffer,))
                t.start()
                t.join()
        else:
            t = threading.Thread(target=self.appendMessage, args=(buffer,))
            t.start()
            t.join()
Exemplo n.º 33
0
    def updateNames(self, buffer):
        names = Message.exportNames(buffer, self.irc.getNamePattern())

        __sortingEnabled = self.usersList.isSortingEnabled()
        self.usersList.setSortingEnabled(False)
        self.usersList.clear()
        for name in names:
            item = QtWidgets.QListWidgetItem()

            txt = ('->'+name) if name == self.username else name
            item.setText(txt)
            self.usersList.addItem(item)
        self.usersList.setSortingEnabled(__sortingEnabled)
Exemplo n.º 34
0
def get_channel_messages(channel_id):
    """指定频道的消息列表.
    支持的query params:
    s - 可选, 相对起始时间, 默认为0, 单位秒
    o - 可选, 相对起始时间的偏移, 默认为10, 单位秒
    l - 可选, 返回的条目限制, 默认为不限制

    :param channel_id:查询的频道id
    :type channel_id:int
    """
    channel = get_channel(channel_id, access_control = True)

    start = parse_int('s', default = 1, condition = lambda s: s >= 1)  # 相对起始时间
    offset = parse_int('o', default = 10, condition = lambda o: o > 0)  # 相对起始时间的偏移
    limit = parse_int('l', default = None, condition = lambda l: l > 0)  # 返回条目限制

    # messages = Message.query.filter(
    #         Message.channel == channel,
    #         Message.offset >= start,
    #         Message.offset <= start + offset
    # ).order_by(
    #         Message.offset,
    #         Message.created_at.desc()
    # ).limit(limit).all()

    # ret = map(lambda msg: msg.to_json(), messages)

    ret = {}
    count = 0
    for o in range(start, start + offset):
        if o > channel.duration:
            break

        messages = Message.get_messages_by_offset(channel.id, o)
        if limit:
            messages = messages[-limit:]
        count += len(messages)
        ret[o] = map(lambda msg: msg.to_json(), messages)

    return success({
        'count': count,
        'messages': ret,
        'start': start,
        'offset': offset,
        'limit': limit
    })