-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
442 lines (403 loc) · 24.6 KB
/
app.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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
import random
import os
import sqlite3
from werkzeug.utils import secure_filename
from flask import Flask, render_template, request, session, g, redirect, flash, url_for
from flask_bcrypt import Bcrypt, generate_password_hash, check_password_hash
from forms.forms import registration, loginForm, createAccount, postStatus, createGroup, groupPost, postComment
from config import Config
from flask_wtf.csrf import CSRFProtect, CSRFError
from datetime import datetime
app = Flask(__name__, template_folder='static/frontend/public/templates')
bcrypt = Bcrypt(app)
app.config.from_object(Config)
csrf = CSRFProtect(app)
SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'
UPLOAD_FOLDER = 'static/frontend/public/profilePhotos'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
ALLOWED_EXTENSIONS = set(['jpg'])
@app.before_request
def before_request():
g.username = None
if 'username' in session:
g.username = session['username']
@app.route('/aboutUs')
def aboutUs():
return render_template('aboutUs.html')
@app.route("/dashboard")
def dashboard():
if g.username:
form = postStatus(request.form)
conn =sqlite3.connect('userData.db')
print ("Opened database successfully")
c = conn.cursor()
c.execute('SELECT author, imageName, postTitle, postContent, category, dateTime FROM accountData INNER JOIN userPost ON userPost.author = accountData.username ORDER BY dateTime DESC')
posts = c.fetchall()
print(posts)
for post in posts:
postTitle = post[2]
postContent = post[3]
category = post[4]
if request.method == 'POST':
conn = sqlite3.connect('userData.db')
print ("User Posts data opened")
c = conn.cursor()
newPost = [(g.username, (form.postTitle.data), (form.postContent.data), (form.category.data))]
with conn:
try:
insertPost = '''INSERT INTO userPost (username, postTitle, postContent, category) VALUES(?,?,?,?)'''
c.executemany(insertPost, newPost)
print ("Insert correctly")
except Exception as e: print(e)
flash((g.username) + " Successfully Posted!!")
return render_template("profile.html", form=form, postTitle=postTitle, postContent=postContent, category=category)
return render_template('dashboard.html', posts=posts, username=g.username)
else:
flash('Please Login to continue')
return redirect('Login')
@app.route("/groups", methods=['GET', 'POST'])
def groups():
if g.username:
form = createGroup(request.form)
conn =sqlite3.connect('userData.db')
print ("Opened database successfully")
c = conn.cursor()
c.execute('SELECT * FROM groups')
groups = c.fetchall()
print(groups)
if request.method == 'POST':
conn = sqlite3.connect('userData.db')
print ("Group data opened")
c = conn.cursor()
groupImage = "public/groupImages/" + form.groupName.data + '.jpg'
newGroup = [((form.groupName.data), (form.groupBio.data), (form.groupType.data), g.username, '150', (groupImage))]
newAdmin = [((form.groupName.data), g.username)]
with conn:
try:
insertPost = '''INSERT INTO groups (groupName, groupBio, groupType, groupMembers, groupSize, groupImage) VALUES(?,?,?,?,?,?)'''
c.executemany(insertPost, newGroup)
createAdmin = '''INSERT INTO group_Admins(adminName, groupName) VALUES(?,?)'''
c.executemany(createAdmin, newAdmin)
print ("Insert correctly")
except Exception as e: print(e)
flash((g.username) + " Successfully Posted!!")
return render_template('groups.html', i=0, groupImage=groupImage, form=form, groups=groups, username=g.username)
return render_template('groups.html', form=form, i=0, groups=groups, username=g.username)
else:
flash('Please Login to continue')
return redirect('Login')
@app.route("/subgroup/id/<subgroup>", methods=['GET', 'POST'])
def subgroup(subgroup):
subgroup=subgroup
print(subgroup)
if g.username:
form = groupPost(request.form)
conn =sqlite3.connect('userData.db')
print ("Opened database successfully")
c = conn.cursor()
findgroup = ('SELECT * FROM groups WHERE groupId LIKE ?')
c.execute(findgroup, subgroup)
groups = c.fetchall()
loadComments = ('SELECT * FROM groupPosts WHERE groupId LIKE ?')
c.execute(loadComments, subgroup)
comments = c.fetchall()
print(groups)
if request.method == 'POST':
conn = sqlite3.connect('userData.db')
print ("Group data opened")
c = conn.cursor()
comment = [(subgroup, g.username, (form.post.data), '0' )]
with conn:
try:
insertPost = '''INSERT INTO groupPosts (groupId, author, comment, votes, dateTime) VALUES(?,?,?,?, datetime('now', 'localtime'))'''
c.executemany(insertPost, comment)
print ("Insert correctly")
except Exception as e: print(e)
flash((g.username) + " Successfully Posted!!")
return render_template('subgroups.html', subgroup=subgroup, form=form, comments=comments, groups=groups, username=g.username)
return render_template('subgroups.html', subgroup=subgroup, form=form, comments=comments, groups=groups, username=g.username)
else:
flash('Please Login to continue')
return redirect('Login')
@app.route("/groupPost/id/<groupPost>", methods=['GET', 'POST'])
def groupPosts(groupPost):
groupPost=groupPost
print(groupPost)
if g.username:
form = postComment(request.form)
conn =sqlite3.connect('userData.db')
print ("Opened database successfully")
c = conn.cursor()
findgroup = ('SELECT * FROM groupPosts WHERE groupId LIKE ?')
c.execute(findgroup, groupPost)
groups = c.fetchone()
loadComments = ('SELECT * FROM groupComments WHERE groupId LIKE ?')
c.execute(loadComments, groupPost)
comments = c.fetchall()
print(groups)
if request.method == 'POST':
conn = sqlite3.connect('userData.db')
print ("Group data opened")
c = conn.cursor()
comment = [(groupPost, g.username, (form.comment.data), '0' )]
with conn:
try:
insertPost = '''INSERT INTO groupComments (groupId, author, comment, votes, dateTime) VALUES(?,?,?,?, datetime('now', 'localtime'))'''
c.executemany(insertPost, comment)
print ("Insert correctly")
except Exception as e: print(e)
flash((g.username) + " Successfully Posted!!")
return render_template('comments.html', groupPost=groupPost, form=form, comments=comments, groups=groups, username=g.username)
return render_template('comments.html', groupPost=groupPost, form=form, comments=comments, groups=groups, username=g.username)
else:
flash('Please Login to continue')
return redirect('Login')
@app.route("/cheer/id/<commentId>")
def cheer(commentId):
if g.username:
commentId=commentId
conn =sqlite3.connect('userData.db')
print ("Opened database successfully")
c = conn.cursor()
checkVotes = ('SELECT dailyVotes FROM accountData WHERE username LIKE ?')
c.execute(checkVotes, [g.username])
votesChecked = c.fetchone()
if int (votesChecked[0]) >= 0:
findgroup = ('SELECT * FROM groupPosts WHERE commentId LIKE ?')
c.execute(findgroup, commentId)
cheer = c.fetchall()
for cheers in cheer:
with conn:
try:
c = conn.cursor()
changeCheers = '''UPDATE groupPosts SET votes = votes + 1 WHERE commentID = ?'''
c.execute(changeCheers, commentId)
updateDailyVotes = '''UPDATE accountData SET dailyVotes = dailyVotes - 1 WHERE username = ?'''
c.execute(updateDailyVotes, [g.username])
print ("Insert correctly")
except Exception as e:print(e)
return redirect('subgroup/id/'+str(cheers[1]))
else:
findgroup = ('SELECT groupId FROM groupPosts WHERE commentId LIKE ?')
c.execute(findgroup, commentId)
groupId = c.fetchone()
flash('You have no more votes left for today!')
return redirect('subgroup/id/'+str(int(groupId[0])))
else:
flash('Please Login to continue')
return redirect('Login')
@app.route("/boo/id/<commentId>")
def boo(commentId):
if g.username:
commentId=commentId
conn =sqlite3.connect('userData.db')
print ("Opened database successfully")
c = conn.cursor()
checkVotes = ('SELECT dailyVotes FROM accountData WHERE username LIKE ?')
c.execute(checkVotes, [g.username])
votesChecked = c.fetchone()
if int(votesChecked[0]) >= 0:
findgroup = ('SELECT * FROM groupPosts WHERE commentId LIKE ?')
c.execute(findgroup, commentId)
cheer = c.fetchall()
for cheers in cheer:
with conn:
try:
c = conn.cursor()
changeCheers = '''UPDATE groupPosts SET votes = votes - 1 WHERE commentID = ?'''
c.execute(changeCheers, commentId)
updateDailyVotes = '''UPDATE accountData SET dailyVotes = dailyVotes - 1 WHERE username = ?'''
c.execute(updateDailyVotes, [g.username])
print ("Insert correctly")
except Exception as e:print(e)
return redirect('subgroup/id/'+str(cheers[1]))
else:
findgroup = ('SELECT groupId FROM groupPosts WHERE commentId LIKE ?')
c.execute(findgroup, commentId)
groupId = c.fetchone()
flash('You have no more votes left for today!')
return redirect('subgroup/id/'+str(int(groupId[0])))
else:
flash('Please Login to continue')
return redirect('Login')
@app.route('/Login/', methods=['GET', 'POST'])
def LogIn():
form = loginForm(request.form)
if request.method == 'POST':
conn = sqlite3.connect('userData.db')
with conn:
c = conn.cursor()
try:
find_user = ("SELECT * FROM accountData WHERE username = ?")
c.execute(find_user, [(form.username.data)])
results =c.fetchall()
userResults = results[0]
if bcrypt.check_password_hash(userResults[2],(form.password.data)):
session['username'] = (form.username.data)
return redirect(url_for('dashboard'))
else:
flash('Either username or password was not recognised')
return render_template('login.html', form=form)
except Exception as e:print(e)
flash('Either username or password was not recognised')
return render_template('login.html', form=form)
return render_template("login.html", form=form)
@app.route("/logout")
def logout():
session['logged_in'] = True
session.clear()
flash("You have successfully logged out.")
return redirect('Login')
@app.route("/dashboard/Post")
def post():
return redirect('dashboard')
@app.route("/profile", methods=['GET', 'POST'])
def profile():
if g.username:
form = postStatus(request.form)
conn =sqlite3.connect('userData.db')
print ("Opened database successfully")
c = conn.cursor()
c.execute('SELECT * FROM accountData WHERE username LIKE (?)', (g.username, ))
results = c.fetchall()
c.execute('SELECT * FROM userPost WHERE author LIKE(?) ORDER BY dateTime DESC', (g.username, ))
posts = c.fetchall()
print(results)
if results:
for row in results:
bio = row[3]
img_url = 'static/' +row[4]
interests = row[5]
if posts:
for post in posts:
postTitle = post[1]
postContent = post[2]
category = post[3]
return render_template("profile.html", form=form, postTitle=postTitle, postContent=postContent, category=category, bio=bio, img_url=img_url, interests=interests, username=g.username)
else:
if request.method == 'POST':
conn = sqlite3.connect('userData.db')
print ("User Posts data opened")
c = conn.cursor()
newPost = [(g.username, (form.postTitle.data), (form.postContent.data), (form.category.data))]
with conn:
try:
insertPost = '''INSERT INTO userPost (author, postTitle, postContent, category, dateTime) VALUES(?,?,?,?, datetime('now', 'localtime'))'''
c.executemany(insertPost, newPost)
print ("Insert correctly")
except Exception as e: print(e)
flash((g.username) + " Successfully Posted!!")
return render_template("profile.html", bio=bio, img_url=img_url, interests=interests, form=form, username=g.username)
else:
flash('Please Login to continue')
return redirect('Login')
@app.route("/profile/user/<user>", methods=['GET', 'POST'])
def profileUserName(user):
user = user
form = postStatus(request.form)
conn =sqlite3.connect('userData.db')
print ("Opened database successfully")
c = conn.cursor()
c.execute('SELECT * FROM accountData WHERE username LIKE (?)', (user, ))
results = c.fetchall()
c.execute('SELECT * FROM userPost WHERE author LIKE(?)', (user, ))
posts = c.fetchall()
print(results)
print(posts)
if request.method == 'POST':
conn = sqlite3.connect('userData.db')
print ("User Posts data opened")
c = conn.cursor()
newPost = [(g.username, (form.postTitle.data), (form.postContent.data), (form.category.data))]
with conn:
try:
insertPost = '''INSERT INTO userPost (author, postTitle, postContent, category, dateTime) VALUES(?,?,?,?, datetime('now', 'localtime'))'''
c.executemany(insertPost, newPost)
print ("Insert correctly")
except Exception as e: print(e)
flash((g.username) + " Successfully Posted!!")
else:
if results:
for row in results:
bio = row[3]
img_url = '../../static/' +row[4]
interests = row[5]
if posts:
for post in posts:
postTitle = post[1]
postContent = post[2]
category = post[3]
return render_template("profile.html", form=form, postTitle=postTitle, postContent=postContent, category=category, bio=bio, img_url=img_url, interests=interests, username=user)
else:
return render_template("profile.html", bio=bio, img_url=img_url, interests=interests, form=form, username=user)
else:
return redirect(404)
@app.route('/', methods=['GET', 'POST'])
@app.route('/signup', methods=['GET', 'POST'])
def SignUp():
if g.username:
return redirect('dashboard')
else:
registerForm = registration(request.form)
if request.method == 'POST':
pw_hash =bcrypt.generate_password_hash(registerForm.password.data)
newEntry = [((registerForm.username.data), pw_hash, (registerForm.emailAddress.data), ' ', 'frontend/public/profilePhotos/placeholder.jpg', '' )]
conn =sqlite3.connect('userData.db')
print ("Opened database successfully")
with conn:
c =conn.cursor()
try:
signupSQL = '''INSERT INTO accountData (username, password, email, bio, imageName, interests, dailyVotes) VALUES(?,?,?,?,?,?,4)'''
c.executemany(signupSQL, newEntry)
print ("Insert correctly")
except:
flash("This is already an account, please log in with those details or change details.")
c.commit()
return render_template("signup.html", form=registerForm)
flash((registerForm.username.data) + " Successfully Registered!")
session['logged_in'] = True
session['username'] = (registerForm.username.data)
return redirect('account')
return render_template("signup.html", form=registerForm)
return render_template('signup.html', form=registerForm)
@app.route('/deleteProfile', methods=['GET', 'POST'])
def deleteProfile():
return redirect("signup")
@app.route('/account', methods=['GET', 'POST'])
def addAccount():
if g.username:
createAccountFrom = createAccount(request.form)
if request.method == 'POST':
conn =sqlite3.connect('userData.db')
print ("Opened database successfully")
bio =(createAccountFrom.bio.data)
f = request.files.get('upload')
imageName = (createAccountFrom.imageName.data)
filename = secure_filename(f.filename)
filetype = filename.split('.')
uploadFile = imageName + ('.') + filetype[1]
f.save(os.path.join(app.config['UPLOAD_FOLDER'], uploadFile))
interests = "Art"
f = request.files.get('photo')
entry = [(bio, 'frontend/public/profilePhotos/'+ imageName + '.' + filetype[1], interests, g.username)]
with conn:
c =conn.cursor()
c.execute('SELECT * FROM accountData WHERE username LIKE (?)', (g.username, ))
try:
sql = ('''UPDATE accountData SET bio=?, imageName=?, interests=? WHERE username =?''')
c.executemany(sql, entry)
message = "You have updated " + g.username + "'s profile."
flash(message)
return redirect('dashboard')
except Exception as e: print(e)
return render_template("createAccount.html", form=createAccountFrom)
else:
return render_template('createAccount.html', form=createAccountFrom)
else:
flash('Please create an account to continue')
return redirect('signup')
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
if __name__ == '__main__':
app.run()