コード例 #1
0
def message(data):
    # store message in db
    user = models.User.query.filter_by(id=data['userid']).first()
    room = models.ChatRooms.query.filter_by(id=data['room']).first()
    message = models.Messages(time=data['time'],
                              message=data['message'],
                              removed=False,
                              edited=False)

    room.messages.append(message)
    user.messages.append(message)
    database.db_session.add(room)
    database.db_session.add(user)
    database.db_session.commit()

    sendMessage = {
        'id': message.id,
        'userId': user.id,
        'roomId': message.roomId,
        'username': user.name,
        'time': message.time,
        'message': message.message,
        'removed': message.removed,
        'edited': message.edited
    }
    emit('roomMessage', sendMessage, room=data['room'])
コード例 #2
0
def sendMessage(nickname):
    #if browse his or her own profile
    if g.user.nickname == nickname:
        user = g.user
        messages = user.get_guser_messages().all()
        return render_template('gusermessage.html',
            messages = messages)
    else: 
    #if browse other's profile    
        user = User.query.filter_by(nickname = nickname).first()
        if user == None:
            flash('User ' + nickname + ' not found.')
            return redirect(url_for('index'))
        messages = user.get_user_messages(g.user).all()
        form = MessagesForm()
        if form.validate_on_submit():
            message = models.Messages(sender_id = g.user.id,
                receiver_id = user.id,
                text = form.text.data, 
                time = datetime.now())
            db.session.add(message)
            db.session.commit()
            flash('Your message is sending!')
            return redirect(url_for('user', nickname=nickname))
        return render_template('message.html',
            form = form,
            messages = messages)
コード例 #3
0
 def post(self):
     event_timestamp = datetime.datetime.strptime(api.payload['timestamp'],
                                                  "%Y-%m-%d %H:%M:%S.%f")
     new_message = models.Messages(date_created=event_timestamp,
                                   dir_id=api.payload['dir_id'],
                                   filename=api.payload['filename'],
                                   message=api.payload['message'])
     models.db.session.add(new_message)
     models.db.session.commit()
     response = {
         "message":
         "event id #" + str(new_message.id) + " logged successfully"
     }
     code = 201
     return response, code
コード例 #4
0
ファイル: views.py プロジェクト: drndrw/flask-message
 def post(self):
     data = request.get_json()
     if data['title'] and data['body'] and data['recipients']:
         try:
             newmessage = models.Messages(str(current_identity),
                                          data['title'], data['body'])
             db.session.add(newmessage)
             db.session.commit()
             for recipient in data['recipients']:
                 newrecipient = models.MessagesRecipients(
                     newmessage.id, recipient)
                 db.session.add(newrecipient)
             db.session.commit()
             return {
                 'status': 'Message {} has been sent.'.format(newmessage.id)
             }
         except Exception as e:
             return {'error': 'An error has occured.', 'info': str(e)}
     else:
         return {'error': 'Please enter all required fields.'}
コード例 #5
0
def view_user(username):
    u = models.User.query.filter_by(username=username).first()
    if not u:
        return render_template('view_user_not_found.html')

    message_form = QuickMessageForm()

    if message_form.send_btn.data and message_form.validate_on_submit():
        if 2 <= len(message_form.message.data) <= 64:
            message = models.Messages(
                sender_id=current_user.id, recp_id=u.id,
                message=str(message_form.message.data), sent=datetime.utcnow())
            db.session.add(message)
            db.session.commit()
            flash('Your message was sent to ' + u.username, 'success')
            return redirect(request.path)
        else:
            flash('Your message must be between 2 and 64 characters long.', 'danger')

    auction_query = u.auctions.filter(models.Auctions.end > datetime.utcnow()).order_by(models.Auctions.posted.asc())

    a = request.args.get('a', type=int, default=1)
    auctions = auction_query.paginate(a, 4).items
    auction_page = Pagination(
        page_parameter='a', a=a, total=auction_query.count(), search=False,
        record_name='auctions', per_page=4, bs_version=3,
        alignment='justify-content-center mt-0 mb-0',
        link_size='sm')

    feedback_query = u.feedback.order_by(models.Feedback.posted.desc())
    pos = feedback_query.filter_by(score=1).count()
    neg = feedback_query.filter_by(score=-1).count()
    score = pos - neg
    perc = 0 if feedback_query.count() == 0 else round(
        (float(pos) / float(feedback_query.count())) * 100.0, 1)
    feedback = feedback_query.limit(3)
    return render_template(
        'view_user.html', u=u, current_auctions=auctions, auction_page=auction_page,
        feedback=feedback, feedback_percentage=perc,
        feedback_score=score, feedback_count=pos + neg, current_user=current_user,
        message_form=message_form)
コード例 #6
0
def get_company_messages(company_guid):
    messages_info = []

    messages_info_from_db = models.Messages.query.filter_by(
        owner_guid=company_guid).all()
    logging.info(
        f'Попытка получить сообщения компании ({company_guid}) из базы данных')
    if messages_info_from_db:
        logging.info(
            f'Сообщения компании ({company_guid}) получены из базы данных')
        for message_info_from_db in messages_info_from_db:
            messages_info.append(message_info_from_db.asdict())
    else:
        logging.info(f'Сообщения компании ({company_guid}) НЕТ в базе данных')
        logging.info(
            f'Попытка получить сообщения компании ({company_guid}) от сервера')
        messages_info_from_parser = parser.get_company_messages(company_guid)
        if len(messages_info_from_parser) > 0:
            logging.info(
                f'Сообщения компании ({company_guid}) получены от сервера')
            for message in messages_info_from_parser:
                if message == {}:
                    continue
                messages_info.append(message)
                message['owner_guid'] = company_guid
                db.session.add(models.Messages(**message))
            db.session.commit()

    if len(messages_info) == 0:
        logging.info(f'Сообщения компании ({company_guid}) НЕ найдены')
    else:
        logging.info(
            f'Найдено {len(messages_info)} сообщений компании ({company_guid})'
        )

    return messages_info
コード例 #7
0
from app import db, models
from datetime import datetime, timedelta

user = models.User.query.filter_by(id=1).first()

a = models.Messages(sender_id=1,
                    receiver_id=2,
                    text='hello, 2nd user.',
                    time=datetime.now())
db.session.add(a)
db.session.commit()
a = models.Messages(sender_id=1,
                    receiver_id=2,
                    text='hello, 2nd message from 1.',
                    time=datetime.now() + timedelta(seconds=1))
db.session.add(a)
db.session.commit()
a = models.Messages(sender_id=2,
                    receiver_id=1,
                    text='hello, 1nd user.',
                    time=datetime.now() + timedelta(seconds=2))
db.session.add(a)
db.session.commit()
a = models.Messages(sender_id=2,
                    receiver_id=1,
                    text='hello, 2nd message from 2.',
                    time=datetime.now() + timedelta(seconds=3))
db.session.add(a)
db.session.commit()

messages = models.Messages.query.all()
コード例 #8
0
def fill_mock_db(MOCKSESSION):
    """fill the mock db with default messages"""
    for msg in TESTMESSAGES:
        MOCKSESSION.add(models.Messages(msg[USER],msg[MESSAGE],msg[TIMESTAMP]))
コード例 #9
0
def messages(conversation):
    if not conversation:
        add_convo = FindUserForm()

        if add_convo.validate_on_submit():
            return redirect(request.path + '/' + str(add_convo.username.data))

        conversations = models.Conversations.query.filter_by(user_id=current_user.id).order_by(
            models.Conversations.last_msg.desc())
        c = request.args.get('c', type=int, default=1)
        convos = conversations.paginate(c, 10).items
        convo_page = Pagination(
            page_parameter='c', c=c, total=conversations.count(), search=False,
            record_name='conversations', per_page=10, bs_version=3,
            alignment='justify-content-center mt-0 mb-0',
            link_size='sm')
        return render_template('messages.html', conversations=convos, convo_page=convo_page, add_convo=add_convo)

    conversant = models.User.query.filter_by(username=conversation).first()
    if not conversant:
        return "User not found"

    message_form = MessageForm()

    if message_form.validate_on_submit():
        convo = models.Conversations.query.filter_by(user_id=current_user.id, conversant=conversant.id).first()
        if not convo:
            convo = models.Conversations(
                user_id=current_user.id, conversant=conversant.id, created=datetime.utcnow())
            db.session.add(convo)
        c_convo = models.Conversations.query.filter_by(user_id=conversant.id, conversant=current_user.id).first()
        if not c_convo:
            c_convo = models.Conversations(
                user_id=conversant.id, conversant=current_user.id, created=datetime.utcnow())
            db.session.add(c_convo)
        sent = datetime.utcnow()
        c_convo.last_msg = sent
        convo.last_msg = sent
        convo.last_read = sent
        message = models.Messages(
            sender_id=current_user.id, recp_id=conversant.id,
            message=str(message_form.message.data), sent=sent)
        db.session.add(message)
        db.session.commit()
        return redirect(request.path)

    convo = models.Conversations.query.filter_by(user_id=current_user.id, conversant=conversant.id).first()

    limit = request.args.get('limit', type=int, default=15)
    total = 0

    messages = None
    if convo:
        messages = models.Messages.query.filter(
            (((models.Messages.sender_id == current_user.id) & (models.Messages.recp_id == conversant.id)) |
             ((models.Messages.sender_id == conversant.id) & (models.Messages.recp_id == current_user.id))) &
            (models.Messages.sent >= convo.created)
        ).order_by(models.Messages.sent.desc())
        total = messages.count()
        messages = list(reversed(messages.limit(limit).all()))
        convo.last_read = datetime.utcnow()
        db.session.commit()

    load_more = min(10, total - limit)

    return render_template('conversation.html', messages=messages, c_name=conversant.username, msg_form=message_form,
                           moremsg=total > limit, limit=limit, load_more=load_more)
コード例 #10
0
def view_dashboard():
    feedback_form = FeedbackForm()
    message_form = QuickMessageForm()

    if feedback_form.feedback_btn.data and feedback_form.validate_on_submit():
        if 10 <= len(feedback_form.feedback.data) <= 50:
            auc = models.Auctions.query.filter_by(id=int(feedback_form.auc_id.data)).first()
            if auc.transaction_step == 0:
                if auc.buyer_id == current_user.id:
                    auc.transaction_step = 2
                elif auc.seller_id == current_user.id:
                    auc.transaction_step = 1
            else:
                auc.transaction_step = 3
            feedback = models.Feedback(
                reviewer=current_user.id, reviewee=int(feedback_form.recp_id.data),
                auction_id=int(feedback_form.auc_id.data), score=int(feedback_form.score.data),
                message=str(feedback_form.feedback.data), posted=datetime.utcnow())
            db.session.add(feedback)
            db.session.commit()
            flash('Your feedback for ' + get_name_by_id(int(feedback_form.recp_id.data)) + ' has been submitted!',
                  'success')
            return redirect(request.path)
        else:
            flash('Feedback message must be between 10 and 50 characters long.', 'danger')

    if message_form.send_btn.data and message_form.validate_on_submit():
        if 2 <= len(message_form.message.data) <= 64:
            message = models.Messages(
                sender_id=current_user.id, recp_id=int(message_form.recp_id.data),
                message=str(message_form.message.data), sent=datetime.utcnow())
            db.session.add(message)
            db.session.commit()
            flash('Your message was sent to ' + get_name_by_id(int(feedback_form.recp_id.data)),
                  'success')
            return redirect(request.path)
        else:
            flash('Your message must be between 2 and 64 characters long.', 'danger')

    u = current_user

    auction_query = u.auctions.filter((models.Auctions.seller_id == u.id) & (models.Auctions.transaction_step == -1))
    a = request.args.get('a', type=int, default=1)
    auctions = auction_query.paginate(a, 5).items
    auction_page = Pagination(
        page_parameter='a', a=a, total=auction_query.count(), search=False,
        record_name='auctions', per_page=5, bs_version=3,
        alignment='justify-content-center',
        link_size='sm')

    messages_query = models.Messages.query.filter((models.Messages.sender_id == u.id) |
                                                  (models.Messages.recp_id == u.id)).order_by(
        models.Messages.sent.desc())
    messages = reversed(messages_query.limit(8).all())

    time_delta = timedelta(days=7)
    recent_query = models.Auctions.query.filter(
        (models.Auctions.end >= datetime.utcnow() - time_delta) & (
            (models.Auctions.buyer_id == u.id) | (models.Auctions.seller_id == u.id)) &
        (models.Auctions.transaction_step >= 0)).order_by(models.Auctions.transaction_step.asc()).order_by(
        models.Auctions.end.desc())
    r = request.args.get('r', type=int, default=1)
    recent = recent_query.paginate(r, 3).items
    recent_page = Pagination(
        page_parameter='r', r=r, total=recent_query.count(), search=False,
        record_name='auctions', per_page=3, bs_version=3,
        alignment='justify-content-center mt-0 mb-0',
        link_size='sm')

    unsold_query = models.Auctions.query.filter(
        (models.Auctions.seller_id == u.id) &
        (models.Auctions.transaction_step < -1)).order_by(models.Auctions.end.desc())
    f = request.args.get('f', type=int, default=1)
    unsold = unsold_query.paginate(f, 5).items
    unsold_page = Pagination(
        page_parameter='f', f=f, total=unsold_query.count(), search=False,
        record_name='auctions', per_page=5, bs_version=3,
        alignment='justify-content-center mt-0 mb-0',
        link_size='sm')

    watch_query = models.Auctions.query.join(models.Watchlists).filter_by(watcher_id=u.id)
    w = request.args.get('w', type=int, default=1)
    watchlist = watch_query.paginate(w, 5).items
    watch_page = Pagination(
        page_parameter='w', w=w, total=unsold_query.count(), search=False,
        record_name='auctions', per_page=5, bs_version=3,
        alignment='justify-content-center mt-0 mb-0',
        link_size='sm')

    feedback_query = u.feedback
    pos = feedback_query.filter_by(score=1).count()
    neg = feedback_query.filter_by(score=-1).count()
    score = pos - neg
    perc = 0 if feedback_query.count() == 0 else round(
        (float(pos) / float(feedback_query.count())) * 100.0, 1)

    return render_template(
        'dashboard.html', u=u, current_auctions=auctions, auction_page=auction_page,
        recent_activity=recent, recent_page=recent_page, feedback_form=feedback_form,
        messages=messages, feedback_percentage=perc, feedback_score=score,
        message_form=message_form, unsold=unsold, unsold_page=unsold_page,
        watchlist=watchlist, watch_page=watch_page)