示例#1
0
    def test_add_like(self):
        """Can a user add a like?"""

        m = Message(id=1111,
                    text="Yo solo sé que no sé nada",
                    user_id=self.testuser2.id)
        db.session.add(m)
        db.session.commit()

        with self.client as c:
            with c.session_transaction() as sess:
                sess[CURR_USER_KEY] = self.testuser.id

            resp = c.post(f"/users/add_like/1111", follow_redirects=True)

            likes = Likes.query.filter(Likes.message_id == 1111).all()
            self.assertEqual(resp.status_code, 200)
            self.assertEqual(len(likes), 1)
            self.assertEqual(likes[0].user_id, self.testuser.id)
示例#2
0
    def test_message_model(self):
        """Does basic model work?"""

        u = User(id=1,
                 email="*****@*****.**",
                 username="******",
                 password="******")

        m = Message(id=1, text="Test Message", timestamp=None, user_id=1)

        db.session.add_all([u, m])
        db.session.commit()

        # Message instance attributes should equal the ones were set, timestamp defaults to datetime now()
        self.assertEqual(m.text, 'Test Message')
        self.assertEqual(m.id, 1)
        self.assertEqual(m.user.username, 'testuser')
        self.assertEqual(m.user.email, '*****@*****.**')
        self.assertNotEqual(m.timestamp, None)
示例#3
0
def flag_add():
    """Add a flag message:

    Show form if GET. If valid, update flag message and redirect to user page.
    """

    if not g.user:
        flash("Access unauthorized.", "danger")
        return redirect("/")

    form = FlagForm()

    if form.validate_on_submit():
        msg = Message(text=form.text.data)
        g.user.messages.append(msg)
        db.session.commit()
        return redirect(f"/")

    return render_template('flags/new.html', form=form)
示例#4
0
def testdb_command():
    db.drop_all()
    db.create_all()

    user1 = User(username='******', password='******')
    db.session.add(user1)

    chatroom1 = ChatRoom(name='Super Awesome Chat Room')
    db.session.add(chatroom1)

    user1.created_rooms.append(chatroom1)

    message1 = Message(creator=user1.username,
                       text="Hello, there!",
                       chatroom=chatroom1.name)
    db.session.add(message1)
    db.session.commit()

    print('Initialized the database.')
示例#5
0
def send_message(request, message_id):
    """
    Render page where students / instructors can go to send a message to other users
    """
    if (message_id != ''):
        message = Message.objects.get(id=message_id)
        form_init = {
            'recipient': message.sender,
            'subject': 'RE: ' + message.subject,
            'text': message.reply_text
        }
    else:
        form_init = {}

    if request.method == "POST":
        form = MessageForm(request.POST)
        if form.is_valid():
            sender = request.user
            recipient = User.objects.get(email=form.data["recipient"])
            subject = form.data["subject"]
            text = form.data["text"].split('\n     >')[0]

            old_reply_text = message.reply_text if message_id != '' else ''
            reply_text = '\n\n'
            reply_lines = ('From: ' + sender.email + '\n' + text +
                           old_reply_text).split('\n')
            for line in reply_lines:
                reply_text = reply_text + '     > ' + line + '\n'

            new_message = Message(sender=sender,
                                  recipient=recipient,
                                  subject=subject,
                                  text=text,
                                  reply_text=reply_text)

            new_message.save()
            return redirect_user_to_homepage(request.user.profile.user_type)
    form = MessageForm(initial=form_init)
    context = {
        "form": form,
    }
    return render(request, "sendmessage.html", context)
示例#6
0
    def setUp(self):
        """Create test client, add sample data."""
        app.config['TESTING'] = True
        app.config['WTF_CSRF_ENABLED'] = False

        self.client = app.test_client()

        u = User.signup(email="*****@*****.**",
                        username="******",
                        password='******',
                        image_url=None)

        db.session.add(u)
        db.session.commit()

        self.user = u

        u_two = User.signup(email="*****@*****.**",
                            username="******",
                            password='******',
                            image_url=None)
        u_two.id = 2
        db.session.add(u_two)
        db.session.commit()

        test_follow = Follows(user_being_followed_id=u.id,
                              user_following_id=u_two.id)
        db.session.add(test_follow)
        db.session.commit()

        test_follow_2 = Follows(user_being_followed_id=u_two.id,
                                user_following_id=u.id)
        db.session.add(test_follow_2)
        db.session.commit()

        test_message = Message(text='i am whiskey',
                               user_id=self.user.id,
                               timestamp=datetime.utcnow())
        db.session.add(test_message)
        db.session.commit()

        self.message = test_message
示例#7
0
def thread(request, **args):
    t = loader.get_template('discussion.view')
    thread = None
    if 'id' in args:
        thread = Thread.objects.get(id=int(args['id']))

    message_form = None

    if thread and thread.openForEvent():
        if request.method == 'POST':
            # Post dictionary needs to be mutable in order to remove the value from the messagebox
            post_vars = {}
            for key in request.POST:
                post_vars[key] = request.POST[key]

            message_form = MessageForm(post_vars)
            if message_form.is_valid():
                message = Message()
                message.content = message_form.cleaned_data['content']
                message_form.data['content'] = ''
                message.time = datetime.now()
                message.user = request.user
                message.thread = thread
                message.save()
        else:
            message_form = MessageForm()

    c = {
        'thread': thread,
        'thread_message': thread.getStatusMessage(),
        'thread_status': thread.getStatus(),
        'messages': None,
        'message_form': message_form,
        'is_authenticated': request.user.is_authenticated()
    }

    if thread:
        messages = Message.objects.filter(thread__id=thread.id)
        c['messages'] = messages

    c.update(csrf(request))
    return HttpResponse(t.render(Context(c)))
示例#8
0
def delete_message(_cursor, user, message_id):
    """
    Deletes message of given ID. It has 4 scenarios:

    Scenarios:
        1. Message ID is not valid.
                Function did not find such message. Prints fail statement.
        2. User requesting deletion is Recipient and message is visibe for him
                Function uses Message static method to make message invisible for Recipient. Sender still can see it.
        3. User requesting deletion is Sender
                Function uses Message method to delete message. It will be deleted also for Recipient
        4. User is neither Sender nor Recipient
                Function prints fail statement

    :param _cursor: parameter passed with connector decorator
    :param user: User class object , user which request delete message
    :param message_id: message ID to be deleted, string type
    :return: function has no return, prints fail/success statemetns
    """
    message = Message().load_message_by_id(_cursor, message_id)

    # Scenario no. 1
    if not message:
        print('Message ID not found, please check and try again')

    # Scenario no. 2
    if message.to_id == user.id and message.is_visible:
        message.recipient_delete_message()
        message.save_to_db(_cursor)
        print('Message deleted!')
        return

    # Scenario no. 3
    elif message.from_id == user.id:
        message.delete_by_sender(_cursor)
        print('Message deleted!')
        return

    # Scenario no. 4
    else:
        print(
            'You cannot delete this message, you are not sender nor recipient')
示例#9
0
def send_message():
    if 'username' in session:
        form = SendMessageForm()

        if request.method == 'POST':
            newmsg = Message(session['username'], form.msg.data,
                             session['chall'])
            db.session.add(newmsg)
            db.session.commit()
            user_msg = "Message sent to Admin"

            return render_template("webstorage/send_message.html",
                                   form=form,
                                   msg=user_msg)

        elif request.method == 'GET':
            return render_template("webstorage/send_message.html", form=form)

    else:
        return redirect(url_for("main.login"))
示例#10
0
    def test_message_likes(self):

        m = Message(text="a warble", user_id=self.user.id)

        self.m = m

        self.testuser = User.signup(username="******",
                                    email="*****@*****.**",
                                    password="******",
                                    image_url=None)

        like = Likes(user_id=self.testuser.id, message_id=self.m.id)

        db.session.add(like)
        db.session.commit()

        l = Likes.query.filter(Likes.message_id == self.m.id).all()

        self.assertEqual(len(l), 1)
        self.assertEqual(l[0].message_id, m.id)
示例#11
0
    def test_delete_like_msg_success(self):
        test_msg = Message(text='heyyyy', user_id=self.test_user0.id)
        db.session.add(test_msg)
        db.session.commit()
        p = test_msg.id

        test_like = Likes(user_id=self.test_user1.id, message_id=p)
        db.session.add(test_like)
        db.session.commit()

        with self.client as c:
            with c.session_transaction() as sess:
                sess[CURR_USER_KEY] = self.test_user1.id

        res = c.post(f"/users/delete_like/{p}", follow_redirects=True)
        html = res.get_data(as_text=True)

        self.assertIn(
            '<div class="alert alert-success">You un-liked harrypotter&#39;s post!</div>',
            html)
示例#12
0
def index():
    form = SayHelloForm()

    db.create_all()  #这一句我不知道放在那合适  案例程序里是放在了command里
    #注意库是要手动建立的,这个只能建立库
    if form.validate_on_submit():

        name = form.name.data
        message = form.message.data

        print(name)
        message_db = Message(name=name, body=message)
        db.session.add(message_db)
        db.session.commit()
        flash('message commit!')
        return redirect(url_for('index'))

    msg = Message.query.order_by(Message.timestamp.desc()).all()

    return render_template('index.html', form=form, msg=msg)
示例#13
0
def messages_add():
    """Add a message:

    Show form if GET. If valid, update message and redirect to user page.
    """

    if not g.user:
        flash("Access unauthorized.", "danger")
        return redirect(url_for('homepage'))

    form = MessageForm()

    if form.validate_on_submit():
        msg = Message(text=form.text.data)
        g.user.messages.append(msg)
        db.session.commit()

        return redirect(url_for('users_show', user_id=g.user.id))

    return render_template('messages/new.html', form=form)
示例#14
0
    def test_logout_delete_message(self):
        """Check if a non user try to delete a message"""

        msg = Message(user_id = self.testuser.id, text="This is a test")

        db.session.add(msg)
        db.session.commit()

        msg_id = msg.id

        with self.client as c:
            
            resp = c.post(f"/messages/{msg_id}/delete", follow_redirects=True)
            html = resp.get_data(as_text=True)

            msg = Message.query.get(msg_id)

            self.assertEqual(resp.status_code, 200)
            self.assertTrue(msg)
            self.assertIn('<div class="alert alert-danger">Access unauthorized.</div>', html)
示例#15
0
def route_message(request):
    """
    消息页面的路由函数
    """
    # log('本次请求的 method', request.method)
    if request.method == 'POST':
        form = request.form()
        msg = Message(form)
        # log('post', form)
        msg.save()
        message_list.append(msg)
        # 应该在这里保存 message_list

    header = 'HTTP/1.x 200 OK\r\nContent-Type: text/html\r\n'
    # body = '<h1>消息版</h1>'
    body = template('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')
示例#16
0
    def new_message(jwt, room_id):
        try:
            active_room = Room.query.get(room_id)
            body = request.get_json()
            content = body.get('content')
            avatar = body.get('avatar')
            print(content)
            new_message = Message(content=content, avatar=avatar)
            if content is None:
                abort(422)
            new_message.room = active_room
            print(new_message.room)
            new_message.insert()

            return jsonify({"success": True,
                            "avatar": new_message.avatar,
                            "message": new_message.content})
        except BaseException:
            print(sys.exc_info())
            abort(422)
    def test_unauthorized_message_delete(self):
        u = User.signup(username="******",
                        email="*****@*****.**",
                        password="******",
                        image_url=None)

        u.id = 54321

        m = Message(id=123,
                    text="testing unauthorized message delete",
                    user_id=self.testuser_id)
        db.session.add_all([u, m])
        db.session.commit()

        with self.client as c:
            with c.session_transaction() as sess:
                sess[CURR_USER_KEY] = 54321

            resp = c.post("/messages/123/delete", follow_redirects=True)
            self.assertEqual(resp.status_code, 200)
示例#18
0
    def test_unauthorized_message_delete(self):

        # A second user that will try to delete the message
        u = User.signup(username="******", email="*****@*****.**", password="******", image_url=None)
        u.id = 2

        #Message is owned by testuser
        m = Message(id=5, text="a test message", user_id = self.testuser.id
        )
        db.session.add_all([u, m])
        db.session.commit()

        with self.client as c:
            with c.session_transaction() as sess:
                sess[CURR_USER_KEY] = 2

            resp = c.post("/messages/5/delete", follow_redirects=True)
            html = resp.get_data(as_text=True)
            self.assertEqual(resp.status_code, 200)
            self.assertIn('<div class="alert alert-danger">Access unauthorized.</div>', html)
示例#19
0
def handle_message(msg):
    global profane
    name = msg['name']
    content = msg['message']

    name_cleaned = profanity.censor(name)
    content_cleaned = profanity.censor(content)

    now = datetime.now().strftime('%A %I:%M:%S %p').lstrip("0").replace(
        " 0", " ")

    message_object = Message(name=name_cleaned,
                             content=content_cleaned,
                             date_posted=now)
    database.session.add(message_object)
    database.session.commit()

    json_data = {'name': name_cleaned, 'content': content_cleaned, 'date': now}

    send({'json_data': json_data}, broadcast=True)
    def test_message_destroy(self):
        """Can you delete a message?"""

        with self.client as c:
            with c.session_transaction() as sess:
                sess[CURR_USER_KEY] = self.testuser.id

            m = Message(text="Hello there", user_id=self.testuser.id)
            m.id = 2323
            db.session.add(m)
            db.session.commit()

            resp = c.post(f"/messages/{m.id}/delete", follow_redirects=True)
            html = resp.get_data(as_text=True)

            count = Message.query.filter_by(id=m.id).count()

            self.assertEqual(resp.status_code, 200)
            self.assertEqual(count, 0)
            self.assertIn("testuser", html)
    def post(self):
        user = users.get_current_user()

        if not user:
            return self.write("You are not logged in!")

        author = self.request.get("name")
        email = user.email()
        message = self.request.get("message")

        if not author:
            author = "Anonymous"

        if "<script>" in message:
            return self.write("Can`t hack me ! :)")      #one way to gight JS injection

        user_details = Message(name=author, email=email, message=message)     #other way is to write .... message=message.replace("<script>"," ")
        user_details.put()                      #save to database

        return self.redirect_to("guestbook-site")
示例#22
0
 def run(self):
     while True:
         try:
             data = self.client.recv(
                 1024)  # This message is sent from client
             if not data:
                 self.client.close()
             else:
                 print(log.new_message + str(self.address) +
                       "-session_id:" + self.session_id + " -message:" +
                       data.decode())
                 common.send_to_all(Message("title", "con", "url"))
         except socket.error as error_msg:
             self.client.close()
             for index, x in enumerate(common.clients):
                 if x.address == self.address:
                     common.clients.pop(index)
             print(log.close_connection + str(self.address) + "." +
                   get_time())
             break
示例#23
0
    def setUp(self):
        """Create test client, add sample data."""

        db.session.rollback()
        User.query.delete()
        Message.query.delete()

        self.client = app.test_client()

        self.testuser = User.signup(username="******",
                                    email="*****@*****.**",
                                    password="******",
                                    image_url=None)

        db.session.commit()

        self.testmsg = Message(user_id=self.testuser.id, text='he1')
        self.testuser.messages.append(self.testmsg)

        db.session.commit()
示例#24
0
    def test_get_msg_ids(self):
        """Test get_msg_ids method"""

        message1 = Message(text="Test message1 here", user_id=self.user.id)

        db.session.add_all([self.message, message1])
        db.session.commit()

        like = Likes(user_id=self.user.id, message_id=self.message.id)
        like1 = Likes(user_id=self.user.id, message_id=message1.id)

        db.session.add_all([like, like1])
        db.session.commit()

        messages = Message.query.all()

        msg_ids = Message.get_liked_msg_ids(messages)

        self.assertEqual(len(msg_ids), 2)
        self.assertIn(self.message.id, msg_ids)
示例#25
0
    def test_message_show(self):

        m = Message(id=10,
                    text="This is a test message",
                    user_id=self.testuser.id)

        db.session.add(m)
        db.session.commit()

        with self.client as c:
            with c.session_transaction() as sess:
                sess[CURR_USER_KEY] = self.testuser.id

            m = Message.query.get(10)

            resp = c.get(f'/messages/{m.id}')
            html = resp.get_data(as_text=True)

            self.assertEqual(resp.status_code, 200)
            self.assertIn("This is a test message", html)
示例#26
0
    def test_message_model(self):
        """Does basic model work?"""

        u = User(email="*****@*****.**",
                 username="******",
                 password="******",
                 id=10000)

        db.session.add(u)

        message = Message(
            text="test",
            user_id=10000,
        )

        db.session.add(message)
        db.session.commit()

        # User should have no messages & no followers
        self.assertEqual(len(message.liked_by), 0)
def sent_to(username, password, toUserName, bodyToUser, creation_date):
    print("SEND A MESSAGE TO A GIVEN USER")
    c = get_connection()
    cursor = c.cursor()
    u = User()
    u.set_password(password, "1")
    if u.get_item_by_login(username, cursor) and u.get_user_by_password(
            username, cursor)[1] == u.hashed_password and u.get_item_by_login(
                toUserName, cursor)[0]:
        m = Message()
        m.body = bodyToUser
        m.creation_date = creation_date
        m.from_user = u.get_user_by_password(username, cursor)[0]
        m.to_user = u.get_user_by_password(toUserName, cursor)[0]
        m.save_message(cursor)
        c.close()
    else:
        print(
            "Nie ma takiego usera lub podałeś złe hasło/login lub nie ma usera do ktorego chcesz cos wyslac"
        )
示例#28
0
    def test_delete_message(self):
        """ Test to delete message from db """

        u1 = User.signup(email="*****@*****.**",
                         username="******",
                         password="******",
                         image_url="/static/images/default-pic.png")

        db.session.add(u1)
        db.session.commit()

        message = Message(text="imsoocool", user_id=u1.id)

        db.session.add(message)
        db.session.commit()

        db.session.delete(message)
        db.session.commit()

        self.assertEqual(u1.messages, [])
示例#29
0
def messages_add():
    """Add a message:

    Show form if GET. If valid, update message and redirect to user page.
    """

    if not g.user:
        flash("Access unauthorized.", "danger")
        return redirect("/")

    form = MessageForm()

    if form.validate_on_submit():
        msg = Message(text=form.data['text'])
        g.user.messages.append(msg)
        db.session.commit()

        return redirect(f"/users/{g.user.id}")

    return render_template('messages/new.html', form=form)
示例#30
0
    def post(self):
        user = users.get_current_user()

        params = {}

        author = user.nickname()
        email = user.email()
        to = self.request.get("to")
        message = self.request.get("message")

        msg_object = Message(author_name=author,
                             email=email,
                             message=message,
                             to=to)
        msg_object.put()

        logout_url = users.create_logout_url('/')
        params["logout_url"] = logout_url

        return self.redirect_to("messenger")