示例#1
0
def create_message(data):
    receiver = data['receiver']
    body = data['body']

    message = Message(receiver=receiver, body=body)
    message.save()
    return message
示例#2
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
示例#3
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])
示例#4
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])
示例#5
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])
示例#6
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
示例#7
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)
示例#8
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])
示例#9
0
def searchMessageByTags(terms, tags):
    q = Q.PriorityQueue()
    db_messages = SlackMessage.query.all()
    messages = []
    # Iterate through each message in the database
    for msg in db_messages:
        # Create a Message object
        message = Message(id=msg.id,
                          url=msg.url,
                          description=msg.description,
                          message_text=msg.message_text,
                          score=0,
                          tags=msg.tags,
                          author=msg.author,
                          annotator=msg.annotator)
        # Check if the Message object has any tag that's in the query tags
        for tag in message.tags:
            # If so add the message into the messages list
            if tag in tags:
                messages.append(message)
                break

    # Now iterate through the list of messages that have relevant tag
    # and score them based on the terms in its description
    for message in messages:
        text = message.description.lower() + " " + message.message_text.lower(
        ) + " " + message.annotator.lower()
        for term in terms:
            if term in text:
                message.setScore(message.getScore() + 1)
        if message.getScore() > 0:
            q.put(message)
    return q
示例#10
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)
示例#11
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
示例#12
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()
示例#13
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
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)
示例#15
0
 def test_returns_expected_starting_new_story(self, story_code_mock, clue_mock, group_mock):
     story_code_mock.build_key.return_value.get.return_value = StoryCode(story_uid="STORY")
     clue_mock.get_by_id.return_value = Clue(text='test')
     clue = Clue(text='test')
     group_mock.return_value.current_clue = clue
     group_mock.gen_uid.return_value = 'abcd'
     user = User()
     result = perform_action(START_STORY, Message(text='start blah'), user, None)
     expected_message_text = [INTRO_INSTRUCTIONS.text, clue.text]
     self.assertEqual(expected_message_text, [m.text for m in result.messages])
示例#16
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
 def on_message(self, message_entity):
     mac.receive_message(self, message_entity)
     
     message = Message(message_entity)
     if message.valid:
         signals.message_received.send(message)
         if helper.is_command(message.message):
             signals.command_received.send(message)
         
     mac.disconnect(self)
示例#18
0
 def get_message(self, messageId):
     with dbapi2.connect(current_app.config['dsn']) as connection:
         cursor = connection.cursor()
         query = "SELECT * FROM MESSAGES WHERE ID = %s"
         cursor.execute(query, (messageId, ))
         message = cursor.fetchall()
         if message is not None and len(message) == 1:
             return Message(message[0][1], message[0][2], message[0][0])
         else:
             return None
示例#19
0
async def append_msg(websocket):
    logger.info("WEBSOKET ACCEPT CONNECTION")
    await websocket.accept()
    msg_txt = await websocket.receive_text()
    msg_json = json.loads(msg_txt)
    message = Message(**msg_json)
    msg_list.add_msg(message)
    await websocket.send_text(MESSAGE_REPLICATION_STATUS_OK)
    await websocket.close()
    logger.info("WEBSOKET CLOSED")
示例#20
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': '操作不当'})
示例#21
0
 def test_answers_clue_properly(self):
     answers = [
         Answer(pattern=r'\w+\s+(?P<second_word>\w+)', next_clue='TWOWORDS'),
         Answer(pattern=r'steve', next_clue="STEVE"),
         Answer(pattern=r'.*', next_clue='CATCHALL'),
     ]
     message = Message(text='test answer')
     next_clue, answer_data = get_next_clue(message, answers)
     self.assertEqual('TWOWORDS', next_clue)
     self.assertEqual({'second_word': 'answer'}, answer_data)
示例#22
0
 def test_requires_matching_receiver(self):
     answers = [
         Answer(pattern=r'.*', next_clue='STORY:FIRSTCLUE', receiver=SECONDARY_SERVER_PHONE),
         Answer(pattern=r'.*', next_clue='STORY:SECONDCLUE')
     ]
     user = MagicMock()
     message = Message(text='correct answer')
     group_mock = Mock(clue=Mock(is_endpoint=False, hint='My Hint', answers=answers))
     result = answer(message, user, group_mock)
     self.assertEqual(CLUE, result.response_type)
     self.assertEqual('STORY:SECONDCLUE', result.group.clue_uid)
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)
示例#24
0
    def test_requires_media(self):
        answers = [
            Answer(pattern=r'.*', next_clue='STORY:FIRSTCLUE', require_media=True),
            Answer(pattern=r'.*', next_clue='STORY:SECONDCLUE')
        ]
        user = MagicMock()
        message_without_media = Message(text='correct answer')
        group_mock = Mock(clue=Mock(is_endpoint=False, hint='My Hint', answers=answers))

        result_without_media = answer(message_without_media, user, group_mock)

        self.assertEqual('STORY:SECONDCLUE', result_without_media.group.clue_uid)
示例#25
0
    def test_matches_if_media_given(self):
        answers = [
            Answer(pattern=r'.*', next_clue='STORY:FIRSTCLUE', require_media=True),
            Answer(pattern=r'.*', next_clue='STORY:SECONDCLUE')
        ]
        user = MagicMock()
        message_with_media = Message(text='correct answer', media_url='www.example.com/caturday.png')
        group_mock = Mock(clue=Mock(is_endpoint=False, hint='My Hint', answers=answers))

        result_with_media = answer(message_with_media, user, group_mock)

        self.assertEqual('STORY:FIRSTCLUE', result_with_media.group.clue_uid)
示例#26
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()
示例#27
0
    def onTextMessage(self, messageProtocolEntity):
        # just print info
        print(" ->>>>>> TEXT MESSAGE RECEIVED!!!!!!")

        # Make message
        message = Message(messageProtocolEntity)
        if message.valid:
            signals.message_received.send(message)
            if helper.is_command(message.message):
                signals.command_received.send(message)

        mac.disconnect(self)
示例#28
0
    def on_message(self, message_entity):
        # Set received (double v) and add to ack queue
        mac.receive_message(self, message_entity)

        # Make message
        message = Message(message_entity)
        if message.valid:
            signals.message_received.send(message)
            if helper.is_command(message.message):
                signals.command_received.send(message)

        mac.disconnect(self)
示例#29
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'))
示例#30
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']