-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathchat.py
163 lines (130 loc) · 4.66 KB
/
chat.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
"""
Chatty Kathy
CS 1520 Fall 2017 Assignment 4
Jordan Grogan
Tu/Th 6:00 Lecture / Th 7:30 Recitation
"""
from flask import Flask, request, session, url_for, redirect, render_template, flash
from models import db, User, Room, Message
from datetime import datetime
from flask_restful import Api
from resources import MessageListResource
app = Flask(__name__)
app.secret_key = "this is a terrible secret key"
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///chat.db'
db.init_app(app)
api = Api(app, prefix="/api")
api.add_resource(MessageListResource, '/messages/', endpoint='messages')
@app.cli.command('initdb')
def initdb_command():
"""Creates the database tables."""
db.drop_all()
db.create_all()
print('Initialized the database.')
# by default, direct to login
@app.route("/", methods=['GET', 'POST'])
def default():
"""Default page."""
if "username" in session:
user = User.query.get(session['user_id'])
if request.method == 'POST':
# Add a Chat Room
if not request.form['name']:
flash("Please enter a chat room name.")
elif Room.query.filter_by(name=request.form['name']).count() > 0:
flash("Sorry, that name is not available.")
else:
db.session.add(Room(name=request.form['name'], creator_id=user.id))
db.session.commit()
flash("The chat room has been added!")
rooms = Room.query.all()
myrooms = user.rooms
return render_template('rooms.html', rooms=rooms, myrooms=myrooms)
return redirect(url_for('login'))
@app.route('/chat')
def chat():
"""Show a chat room."""
if "username" in session:
if request.args.get('room'):
# Set the user's current room = currentRoom ID
user = User.query.get(session['user_id'])
user.currentRoom = request.args.get('room')
db.session.commit()
room = Room.query.get(request.args.get('room'))
messages = Message.query.filter_by(room_id=room.id).order_by(Message.timestamp).all()
session["lastPolled"] = datetime.now().strftime("%Y-%m-%dT%H:%M:%S.%f")
print("Setting Last Polled:", session["lastPolled"])
return render_template('chat.html', room=room, messages=messages)
else:
flash("Error displaying chat room.")
else:
flash("You do not have permission to access this page.")
return redirect(url_for('default'))
@app.route("/login", methods=['GET', 'POST'])
def login():
"""Logs the user in."""
# first check if the user is already logged in
if "username" in session:
flash("Already logged in!")
return redirect(url_for('default'))
# if not, and the incoming request is via POST try to log them in
elif request.method == 'POST':
user = User.query.filter_by(username=request.form['username']).first()
if user is None:
flash("Invalid username, please try again.")
elif user.password != request.form['password']:
flash("Invalid password, please try again.")
else:
session['user_id'] = user.id
session['username'] = user.username
return redirect(url_for('default'))
return render_template('login.html')
@app.route("/logout")
def logout():
"""Logs the user out."""
# if logged in, log out, otherwise offer to log in
if "username" in session:
session.clear()
flash("Successfully logged out!")
else:
flash("Not currently logged in!")
return redirect(url_for("login"))
@app.route('/register', methods=['GET', 'POST'])
def register():
"""Registers the user."""
if "username" in session:
return redirect(url_for('default'))
if request.method == 'POST':
if not request.form['username']:
flash("Please enter a username.")
elif not request.form['password']:
flash("Plase enter a password.")
elif User.query.filter_by(username = request.form['username']).count() > 0:
flash("Sorry, that username is already taken.")
else:
db.session.add(User(username=request.form['username'], password=request.form['password']))
db.session.commit()
flash("You were successfully registered and can login now.")
return redirect(url_for('login'))
return render_template('register.html')
@app.route("/error")
def error():
"""Javascript will redirect to this page to flash an error message and redirect back to default."""
if int(request.args.get('error')) == 1:
flash("That chat room has been deleted and no longer exists.")
elif int(request.args.get('error')) == 2:
flash("You cannot be in more than one chat room at once.")
return redirect(url_for("default"))
@app.route("/delete")
def delete():
"""Logs the user out."""
room_id = int(request.args.get('room'))
r = Room.query.get(room_id)
# check ownership
if r and r.creator_id == session["user_id"]:
db.session.delete(r)
db.session.commit()
flash("That chat room has been deleted.")
else:
flash("You do not have permission to delete that chat room.")
return redirect(url_for("default"))