serve.py
16.3 KB
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
447
448
449
450
451
'''
Tornado Webserver
'''
# python standard library
import asyncio
import base64
from logging import getLogger
import mimetypes
from os.path import join, dirname, expanduser
import signal
import sys
from typing import List, Optional, Union
import uuid
# third party libraries
import tornado.httpserver
import tornado.ioloop
import tornado.web
from tornado.escape import to_unicode
# this project
from aprendizations.renderer_markdown import md_to_html
from aprendizations.learnapp import LearnException
# setup logger for this module
logger = getLogger(__name__)
# ============================================================================
# Handlers
# ============================================================================
class BaseHandler(tornado.web.RequestHandler):
'''Base handler common to all handlers.'''
def initialize(self, app):
self.app = app
def get_current_user(self):
'''called on every method decorated with @tornado.web.authenticated'''
cookie = self.get_secure_cookie('aprendizations_user')
return None if cookie is None else to_unicode(cookie)
# ----------------------------------------------------------------------------
class LoginHandler(BaseHandler):
'''Handles /login'''
def get(self) -> None:
'''Login page'''
self.render('login.html', error='')
async def post(self):
'''Authenticate and redirect to application if successful'''
uid = self.get_body_argument('uid') or ''
pw = self.get_body_argument('pw')
loop = tornado.ioloop.IOLoop.current()
login_ok = await self.app.login(uid, pw, loop)
if login_ok:
self.set_secure_cookie('aprendizations_user', uid)
self.redirect('/')
else:
self.render('login.html', error='Número ou senha incorrectos')
# ----------------------------------------------------------------------------
class LogoutHandler(BaseHandler):
'''Handle /logout'''
@tornado.web.authenticated
def get(self) -> None:
'''Clear cookies and user session'''
self.app.logout(self.current_user)
self.clear_cookie('aprendizations_user')
self.redirect('/')
# ----------------------------------------------------------------------------
class ChangePasswordHandler(BaseHandler):
'''Handles password change'''
@tornado.web.authenticated
async def post(self) -> None:
'''Try to change password and show success/fail status'''
userid = self.current_user
passwd = self.get_body_arguments('new_password')[0] # FIXME porque [0]?
ok = await self.app.change_password(userid, passwd)
notification = self.render_string('notification.html', ok=ok)
self.write({'msg': to_unicode(notification)})
# ----------------------------------------------------------------------------
class RootHandler(BaseHandler):
'''Handle / (root)'''
@tornado.web.authenticated
def get(self) -> None:
'''Redirect to main entrypoint'''
self.redirect('/courses')
# ----------------------------------------------------------------------------
class CoursesHandler(BaseHandler):
'''Handles /courses'''
def set_default_headers(self, *_) -> None:
self.set_header('Cache-Control', 'no-cache')
@tornado.web.authenticated
def get(self) -> None:
'''Render available courses'''
uid = self.current_user
self.render('courses.html',
uid=uid,
name=self.app.get_student_name(uid),
courses=self.app.get_courses(),
# courses_progress=
)
# ============================================================================
class CourseHandler2(BaseHandler):
@tornado.web.authenticated
def get(self, course_id) -> None:
''' Handles /course/... - start course and show topics'''
uid = self.current_user
logger.debug('[CourseHandler2] uid="%s", course_id="%s"', uid, course_id)
if course_id == '':
course_id = self.app.get_current_course_id(uid)
try:
self.app.start_course(uid, course_id)
except LearnException:
self.redirect('/courses')
self.render('maintopics-table2.html',
uid=uid,
name=self.app.get_student_name(uid),
state=self.app.get_student_state(uid),
course_id=course_id,
course=self.app.get_course(course_id)
)
# ============================================================================
class CourseHandler(BaseHandler):
'''Show topics for a particular course'''
@tornado.web.authenticated
def get(self, course_id) -> None:
''' Handles /course/... - start course and show topics'''
uid = self.current_user
logger.debug('[CourseHandler] uid="%s", course_id="%s"', uid, course_id)
if course_id == '':
course_id = self.app.get_current_course_id(uid)
try:
self.app.start_course(uid, course_id)
except LearnException:
self.redirect('/courses')
self.render('maintopics-table.html',
uid=uid,
name=self.app.get_student_name(uid),
state=self.app.get_student_state(uid),
course_id=course_id,
course=self.app.get_course(course_id)
)
# ============================================================================
class TopicHandler(BaseHandler):
'''Handle topic'''
def set_default_headers(self, *_) -> None:
self.set_header('Cache-Control', 'no-cache')
@tornado.web.authenticated
async def get(self, topic) -> None:
'''Handles get /topic/... - start topic'''
uid = self.current_user
logger.debug('[TopicHandler] %s', topic)
try:
await self.app.start_topic(uid, topic) # FIXME GET should not modify state...
except KeyError:
self.redirect('/topics')
self.render('topic.html',
uid=uid,
name=self.app.get_student_name(uid),
course_id=self.app.get_current_course_id(uid),
)
# ============================================================================
class FileHandler(BaseHandler):
'''Serves files from the /public directory of a topic'''
@tornado.web.authenticated
async def get(self, filename) -> None:
'''Serve file from the /public directory of a topic'''
uid = self.current_user
public_dir = self.app.get_current_public_dir(uid)
filepath = expanduser(join(public_dir, filename))
logger.debug('[FileHandler] uid=%s, public_dir=%s, filepath=%s',
uid, public_dir, filepath)
try:
with open(filepath, 'rb') as file:
data = file.read()
except OSError:
logger.error('Error reading: %s', filepath)
raise
content_type = mimetypes.guess_type(filename)[0]
if content_type is not None:
self.set_header("Content-Type", content_type)
self.write(data)
await self.flush()
# ============================================================================
class QuestionHandler(BaseHandler):
'''Responds to AJAX to get a JSON question'''
templates = {
'checkbox': 'question-checkbox.html',
'radio': 'question-radio.html',
'text': 'question-text.html',
'text-regex': 'question-text.html',
'numeric-interval': 'question-text.html',
'textarea': 'question-textarea.html',
# -- information panels --
'information': 'question-information.html',
'success': 'question-information.html',
'warning': 'question-information.html',
'alert': 'question-information.html',
}
# ------------------------------------------------------------------------
@tornado.web.authenticated
async def get(self) -> None:
'''Get question to render or an animated trophy'''
logger.debug('[QuestionHandler]')
user = self.current_user
question = await self.app.get_question(user)
# show current question
if question is not None:
qhtml = self.render_string(self.templates[question['type']],
question=question, md=md_to_html)
response = {
'method': 'new_question',
'params': {
'type': question['type'],
'question': to_unicode(qhtml),
'progress': self.app.get_student_progress(user),
'tries': question['tries'],
}
}
# show animated trophy
else:
finished = self.render_string('finished_topic.html')
response = {
'method': 'finished_topic',
'params': {
'question': to_unicode(finished)
}
}
self.write(response)
# ------------------------------------------------------------------------
@tornado.web.authenticated
async def post(self) -> None:
'''
Correct answer and return status: right, wrong, try_again
Does not move to the next question.
'''
user = self.current_user
answer = self.get_body_arguments('answer') # list
qid = self.get_body_arguments('qid')[0]
logger.debug('[QuestionHandler] answer=%s', answer)
# --- check if browser opened different questions simultaneously
if qid != self.app.get_current_question_id(user):
logger.warning('User %s desynchronized questions', user)
self.write({
'method': 'invalid',
'params': {
'msg': ('Esta pergunta já não está activa. '
'Tem outra janela aberta?')
}
})
return
# --- answers are in a list. fix depending on question type
qtype = self.app.get_student_question_type(user)
ans: Optional[Union[List, str]]
if qtype in ('success', 'information', 'info'):
ans = None
elif qtype == 'radio' and not answer:
ans = None
elif qtype != 'checkbox': # radio, text, textarea, ...
ans = answer[0]
else:
ans = answer
# --- check answer (nonblocking) and get corrected question and action
question = await self.app.check_answer(user, ans)
# --- build response
response = {'method': question['status'], 'params': {}}
if question['status'] == 'right': # get next question in the topic
comments = self.render_string('comments-right.html',
comments=question['comments'],
md=md_to_html)
solution = self.render_string('solution.html',
solution=question['solution'],
md=md_to_html)
response['params'] = {
'type': question['type'],
'progress': self.app.get_student_progress(user),
'comments': to_unicode(comments),
'solution': to_unicode(solution),
'tries': question['tries'],
}
elif question['status'] == 'try_again':
comments = self.render_string('comments.html',
comments=question['comments'],
md=md_to_html)
response['params'] = {
'type': question['type'],
'progress': self.app.get_student_progress(user),
'comments': to_unicode(comments),
'tries': question['tries'],
}
elif question['status'] == 'wrong': # no more tries
comments = self.render_string('comments.html',
comments=question['comments'],
md=md_to_html)
solution = self.render_string(
'solution.html', solution=question['solution'], md=md_to_html)
response['params'] = {
'type': question['type'],
'progress': self.app.get_student_progress(user),
'comments': to_unicode(comments),
'solution': to_unicode(solution),
'tries': question['tries'],
}
else:
logger.error('Unknown question status: %s', question["status"])
self.write(response)
# ----------------------------------------------------------------------------
class RankingsHandler(BaseHandler):
'''
Handles rankings page
'''
@tornado.web.authenticated
def get(self) -> None:
'''
Renders list of students that have answers in this course.
'''
uid = self.current_user
current_course = self.app.get_current_course_id(uid)
course_id = self.get_query_argument('course', default=current_course)
rankings = self.app.get_rankings(uid, course_id)
self.render('rankings.html',
uid=uid,
name=self.app.get_student_name(uid),
rankings=rankings,
course_id=course_id,
course_title=self.app.get_student_course_title(uid),
# FIXME get from course var
)
# ----------------------------------------------------------------------------
# Signal handler to catch Ctrl-C and abort server
# ----------------------------------------------------------------------------
def signal_handler(*_) -> None:
'''
Catches Ctrl-C and stops webserver
'''
reply = input(' --> Stop webserver? (yes/no) ')
if reply.lower() == 'yes':
tornado.ioloop.IOLoop.current().stop()
logger.critical('Webserver stopped.')
sys.exit(0)
# ----------------------------------------------------------------------------
async def webserver(app, ssl, port: int = 8443, debug: bool = False) -> None:
'''
Runs webserver until a SIGINT signal (Ctrl-C) is received.
'''
# --- create web application
handlers = [
(r'/login', LoginHandler, dict(app=app)),
(r'/logout', LogoutHandler, dict(app=app)),
(r'/change_password', ChangePasswordHandler, dict(app=app)),
(r'/question', QuestionHandler, dict(app=app)), # render question
(r'/rankings', RankingsHandler, dict(app=app)), # rankings table
(r'/topic/(.+)', TopicHandler, dict(app=app)), # start topic
(r'/file/(.+)', FileHandler, dict(app=app)), # serve file
(r'/courses', CoursesHandler, dict(app=app)), # show available courses
(r'/course/(.*)', CourseHandler, dict(app=app)), # show topics from course
(r'/course2/(.*)', CourseHandler2, dict(app=app)), # show topics from course FIXME
(r'/', RootHandler, dict(app=app)), # redirects
]
settings = {
'template_path': join(dirname(__file__), 'templates'),
'static_path': join(dirname(__file__), 'static'),
'static_url_prefix': '/static/',
'xsrf_cookies': True,
'cookie_secret': base64.b64encode(uuid.uuid4().bytes),
'login_url': '/login',
'debug': debug,
}
webapp = tornado.web.Application(handlers, **settings)
logger.info('Web application created (tornado.web.Application)')
# --- create tornado http server
try:
httpserver = tornado.httpserver.HTTPServer(webapp, ssl_options=ssl)
except ValueError:
logger.critical('Certificates cert.pem and privkey.pem not found')
sys.exit(1)
logger.debug('HTTPS server started')
try:
httpserver.listen(port)
except OSError:
logger.critical('Cannot bind port %d. Already in use?', port)
sys.exit(1)
logger.info('Listening on port %d... (Ctrl-C to stop)', port)
# --- set signal handler for Control-C
signal.signal(signal.SIGINT, signal_handler)
# --- run event loop (and tornado webserver)
await asyncio.Event().wait()