-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
446 lines (349 loc) · 14.3 KB
/
server.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
443
444
445
446
from jinja2 import StrictUndefined
from flask import Flask, jsonify, render_template, redirect, request, flash, session, g
from flask_debugtoolbar import DebugToolbarExtension
from flask.ext.login import LoginManager, UserMixin, \
login_required, login_user, logout_user
from model import connect_to_db, db, User, Project, Status, Image
# import datetime
import tracker
import api
import requests
import os
from seed import sync_projects
import datetime
from sqlalchemy.sql.functions import func
app = Flask(__name__)
JS_TESTING_MODE = False
# Required to use Flask sessions and the debug toolbar
app.secret_key = "secret"
# Raise error if undefine Jinja variable
app.jinja_env.undefined = StrictUndefined
# flask-login
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "login"
@app.before_request
def add_tests():
g.jasmine_tests = JS_TESTING_MODE
@app.route('/')
def homepage():
""" View homepage """
# session['user'] = 463097
return render_template("homepage.html")
@app.route('/user')
def view_profile():
""" view user profile page """
# check if there is a current user
if 'user' not in session:
return redirect("/login")
# query for current user
user = User.query.get(int(session['user']))
return render_template("user.html", user=user)
@app.route('/user/update', methods=["POST"])
def update():
# Update the database
user = User.query.get(int(session['user']))
user.phone_num = str(request.form.get('phone'))
user.update_time = int(request.form.get('frequency'))
user.subscribed = bool(request.form.get('subscribed'))
db.session.commit()
return "User Successfuly Updated!"
@app.route('/logout')
def logout():
""" log out user from the session """
# remove any users from the session
session.clear()
# redirect back to login
return redirect('/login')
@app.route('/login', methods=['GET'])
def login():
""" show the login form """
return render_template("login.html")
@app.route('/login', methods=['POST'])
def check_user():
""" log the user in """
# get the user name from the post form
user = request.form.get("username")
password = request.form.get("password")
route = tracker.check_login(user, password)
return redirect(route)
# @app.route("/login", methods=["GET", "POST"])
# def login():
# if request.method == 'POST':
# username = request.form['username']
# password = request.form['password']
# user = tracker.check_login(username, password)
# if user:
# login_user(user)
# return redirect('/user')
# else:
# return redirect('/login')
# else:
# return render_template("login.html")
@app.route('/projects')
def view_projects():
""" View the current users projects """
# check if there is a current user
if 'user' not in session:
return redirect("/login")
# Get finished projects
fin_projects = db.session.query(Project).join(Status).filter(
Project.user_id == session['user'],
Status.status == "Finished").all()
# Get hibernating projects
hib_projects = db.session.query(Project).join(Status).filter(
Project.user_id == session['user'],
Status.status == "Hibernating").all()
# Get frogged projects
frog_projects = db.session.query(Project).join(Status).filter(
Project.user_id == session['user'],
Status.status == "Frogged").all()
# Get the projects for the current user and are in progress
wip_projects = db.session.query(Project).join(Status).filter(
Project.user_id == session['user'],
Status.status == "In progress").order_by(Project.updated_at).all()
# get project update time
freq = db.session.query(User.update_time).filter(
User.user_id == session['user']).one()[0]
# sort the in progress projects into 2 groups based on update needs
need_update, updated = tracker.sort_projects_by_update(wip_projects, freq)
projects_by_type = {"finished": fin_projects,
"hibernate": hib_projects,
"frogged": frog_projects,
"need update": need_update,
"updated": updated}
counts = {k: len(v) for k, v in projects_by_type.items()}
data_dict = {
"labels": [k for k in sorted(counts.keys())],
"datasets": [
{
"data": [v for k, v in sorted(counts.items())],
"backgroundColor": [
"#FF6384",
"#36A2EB",
"red",
"blue",
"green",
],
"hoverBackgroundColor": [
"#FF6384",
"#36A2EB",
]
}]
}
wip_dict = {
"labels": ["WIP"],
"datasets": [
{
"label": "Need Update",
"data": [counts['need update']],
"backgroundColor": [
"#B56357"
],
"hoverBackgroundColor": [
"#FF6F59"
],
"hoverBackgroundColor": [
"#FF6F59"
]
},
{
"label": "Updated",
"data": [counts['updated']],
"backgroundColor": [
"#B4DBC0"
],
"hoverBackgroundColor": [
"#B4DBC0"
"#43AA8B"
],
"hoverBackgroundColor": [
"#43AA8B"
]
}]}
return render_template("projects.html",
finished=fin_projects,
hibernate=hib_projects,
frogged=frog_projects,
needUpdate=need_update,
updated=updated,
counts=counts,
dict=data_dict,
wip=wip_dict,
freq=freq)
@app.route('/projects/<projectid>', methods=['GET'])
def view_details(projectid):
""" Show the project details and update form for a given project"""
# get the project for that project id
project_images = Project.query.options(db.joinedload('images'), db.joinedload('status')).filter(
Project.project_id == projectid).one()
project = project_images
images = project.images
# get username
username = db.session.query(User.username).filter(User.user_id == session['user']).one()[0]
# show the project details page
return render_template('project_details.html',
project=project,
images=images,
username=username)
@app.route('/projects/<projectid>', methods=['POST'])
def update_project(projectid):
""" Update the database with form inputs """
up_notes = request.form.get('notes')
up_status = request.form.get('status')
up_image = request.form.get('img-url')
up_progress = request.form.get('progress')
# get the project for that project id
project = Project.query.get(int(projectid))
# get the current user's user object
user = User.query.get(session['user'])
# update the db
tracker.post_project_db_update(project, up_notes,
up_status, up_image,
user, up_progress)
# update api/ ravelry project page
api.post_project_api_update(project, up_notes, up_status, up_progress, user)
api.post_add_image(project, user, up_image)
# flash message about update
flash("Update Successful")
# go to the project page
return redirect("/projects/%s" % (projectid))
@app.route('/sync')
def sync():
user = request.args.get('user')
print user
return sync_projects(user)
@app.route('/projects-react')
def react_page():
# check if there is a current user
if 'user' not in session:
return redirect("/login")
# get project update time
freq = db.session.query(User.update_time).filter(
User.user_id == session['user']).one()[0]
NOW = datetime.datetime.now()
# Get finished projects
fin_projects = db.session.query(func.count(Project.project_id)).join(Status).filter(
Project.user_id == session['user'],
Status.status == "Finished").first()[0]
# Get hibernating projects
hib_projects = db.session.query(func.count(Project.project_id)).join(Status).filter(
Project.user_id == session['user'],
Status.status == "Hibernating").first()[0]
# Get frogged projects
frog_projects = db.session.query(func.count(Project.project_id)).join(Status).filter(
Project.user_id == session['user'],
Status.status == "Frogged").first()[0]
# Get the projects for the current user and are in progress
need_update = db.session.query(func.count(Project.project_id)).join(Status).filter(
Project.user_id == session['user'],
Project.updated_at < (NOW - datetime.timedelta(days = freq)),
Status.status == "In progress").first()[0]
updated = db.session.query(func.count(Project.project_id)).join(Status).filter(
Project.user_id == session['user'],
Project.updated_at > (NOW - datetime.timedelta(days = freq)),
Status.status == "In progress").first()[0]
counts = {"finished": int(fin_projects),
"hibernate": int(hib_projects),
"frogged": int(frog_projects),
"need update": int(need_update),
"updated": int(updated)}
# counts = {k: len(v) for k,v in projects_by_type.items()}
data_dict = {
"labels": [k for k in sorted(counts.keys())],
"datasets": [
{
"data": [v for k, v in sorted(counts.items())],
"backgroundColor": [
"#FF6384",
"#36A2EB",
"red",
"blue",
"green",
],
"hoverBackgroundColor": [
"#FF6384",
"#36A2EB",
]
}]
}
wip_dict = {
"labels": ["WIP"],
"datasets": [
{
"label": "Need Update",
"data": [counts['need update']],
"backgroundColor": [
"blue"
],
"hoverBackgroundColor": [
"#B56357"
]
},
{
"label": "Updated",
"data": [counts['updated']],
"backgroundColor": [
"green"
],
"hoverBackgroundColor": [
"#B4DBC0"
]
}] }
return render_template("react-projects.html",
finished=fin_projects,
hibernate=hib_projects,
frogged=frog_projects,
needUpdate= need_update,
updated=updated,
counts=counts,
dict=data_dict,
wip=wip_dict,
freq=freq)
@app.route('/projects-json/<status>')
def project_list(status):
# # Get the projects for the current user and are in progress
# wip_projects = db.session.query(Project).join(Status).filter(
# Project.user_id == session['user'],
# Status.status == "In progress").order_by(Project.updated_at).all()
# # get project update time
# freq = db.session.query(User.update_time).filter(
# User.user_id == session['user']).one()[0]
# # sort the in progress projects into 2 groups based on update needs
# need_update, updated = tracker.sort_projects_by_update(wip_projects, freq)
session['user'] = 463097
NOW = datetime.datetime.now()
if str(status) == "Need Update":
status = 'In progress'
freq = db.session.query(User.update_time).filter(
User.user_id == session['user']).one()[0]
projects = db.session.query(Project.name, Project.project_id).join(Status).filter(
Project.user_id == session['user'],
Project.updated_at < (NOW - datetime.timedelta(days = freq)),
Status.status == status).all()
elif str(status) == 'Updated':
status = u'In progress'
freq = db.session.query(User.update_time).filter(
User.user_id == session['user']).one()[0]
projects = db.session.query(Project.name, Project.project_id).join(Status).filter(
Project.user_id == session['user'],
Project.updated_at > (NOW - datetime.timedelta(days = freq)),
Status.status == status).all()
else:
projects = db.session.query(Project.name, Project.project_id).join(Status).filter(
Project.user_id == session['user'],
Status.status == status).all()
return jsonify(projects=projects)
if __name__ == "__main__": # pragma: no cover
import sys
if sys.argv[-1] == "jstest":
JS_TESTING_MODE = True
# set up debug toolbar
app.debug = True
app.jinja_env.auto_reload = app.debug
app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False
connect_to_db(app)
# Use the DebugToolbar
DebugToolbarExtension(app)
# run the app
app.run(port=5000, host='0.0.0.0')