serve.py 18.4 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 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
#!/usr/bin/env python3

# python standard library
from os import path
import os
import sys
import base64
import uuid
import logging.config
import argparse
import mimetypes
import signal
import functools
import ssl
import asyncio
# from typing import NoReturn

# third party libraries
import tornado.ioloop
import tornado.web
import tornado.httpserver
from tornado.escape import to_unicode

# this project
from .learnapp import LearnApp
from .tools import load_yaml, md_to_html
from . import APP_NAME


# ----------------------------------------------------------------------------
# Decorator used to restrict access to the administrator only
# ----------------------------------------------------------------------------
def admin_only(func):
    @functools.wraps(func)
    def wrapper(self, *args, **kwargs):
        if self.current_user != '0':
            raise tornado.web.HTTPError(403)  # forbidden
        else:
            func(self, *args, **kwargs)
    return wrapper


# ============================================================================
# WebApplication - Tornado Web Server
# ============================================================================
class WebApplication(tornado.web.Application):
    def __init__(self, learnapp, debug=False):
        handlers = [
            (r'/login',         LoginHandler),
            (r'/logout',        LogoutHandler),
            (r'/change_password', ChangePasswordHandler),
            (r'/question',      QuestionHandler),       # renders each question
            (r'/rankings',      RankingsHandler),       # student rankings
            (r'/topic/(.+)',    TopicHandler),          # start a topic
            (r'/file/(.+)',     FileHandler),           # serve files
            (r'/',              RootHandler),           # show list of topics
        ]
        settings = {
            'template_path': path.join(path.dirname(__file__), 'templates'),
            'static_path':   path.join(path.dirname(__file__), 'static'),
            'static_url_prefix': '/static/',
            'xsrf_cookies': True,
            'cookie_secret': base64.b64encode(uuid.uuid4().bytes),
            'login_url': '/login',
            'debug': debug,
        }
        super().__init__(handlers, **settings)
        self.learn = learnapp


# ============================================================================
# Handlers
# ============================================================================

# ----------------------------------------------------------------------------
# Base handler common to all handlers.
# ----------------------------------------------------------------------------
class BaseHandler(tornado.web.RequestHandler):
    @property
    def learn(self):
        return self.application.learn

    def get_current_user(self):
        cookie = self.get_secure_cookie('user')
        if cookie:
            uid = cookie.decode('utf-8')
            counter = self.get_secure_cookie('counter').decode('utf-8')
            if counter == str(self.learn.get_login_counter(uid)):
                return uid


# ----------------------------------------------------------------------------
# /rankings
# ----------------------------------------------------------------------------
class RankingsHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        uid = self.current_user
        rankings = self.learn.get_rankings(uid)
        self.render('rankings.html',
                    appname=APP_NAME,
                    uid=uid,
                    name=self.learn.get_student_name(uid),
                    rankings=rankings)


# ----------------------------------------------------------------------------
# /auth/login
# ----------------------------------------------------------------------------
class LoginHandler(BaseHandler):
    def get(self):
        self.render('login.html',
                    appname=APP_NAME,
                    error='')

    async def post(self):
        uid = self.get_body_argument('uid').lstrip('l')
        pw = self.get_body_argument('pw')

        login_ok = await self.learn.login(uid, pw)

        if login_ok:
            counter = str(self.learn.get_login_counter(uid))
            self.set_secure_cookie('user', uid)
            self.set_secure_cookie('counter', counter)
            self.redirect('/')
        else:
            self.render('login.html',
                        appname=APP_NAME,
                        error='Número ou senha incorrectos')


# ----------------------------------------------------------------------------
# /auth/logout
# ----------------------------------------------------------------------------
class LogoutHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        self.clear_cookie('user')
        self.clear_cookie('counter')
        self.redirect('/')

    def on_finish(self):
        self.learn.logout(self.current_user)


# ----------------------------------------------------------------------------
class ChangePasswordHandler(BaseHandler):
    @tornado.web.authenticated
    async def post(self):
        uid = self.current_user
        pw = self.get_body_arguments('new_password')[0]

        changed_ok = await self.learn.change_password(uid, pw)
        if changed_ok:
            notification = self.render_string(
                'notification.html',
                type='success',
                msg='A password foi alterada!'
                )
        else:
            notification = self.render_string(
                'notification.html',
                type='danger',
                msg='A password não foi alterada!'
                )

        self.write({'msg': to_unicode(notification)})


# ----------------------------------------------------------------------------
# /   (main page)
# Shows a list of topics and proficiency (stars, locked).
# ----------------------------------------------------------------------------
class RootHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        uid = self.current_user
        self.render('maintopics-table.html',
                    appname=APP_NAME,
                    uid=uid,
                    name=self.learn.get_student_name(uid),
                    state=self.learn.get_student_state(uid),
                    title=self.learn.get_title(),
                    )


# ----------------------------------------------------------------------------
# /topic/...
# Start a given topic
# FIXME should not change state...
# ----------------------------------------------------------------------------
class TopicHandler(BaseHandler):
    @tornado.web.authenticated
    async def get(self, topic):
        uid = self.current_user

        try:
            await self.learn.start_topic(uid, topic)
        except KeyError:
            self.redirect('/')
        else:
            self.render('topic.html',
                        appname=APP_NAME,
                        uid=uid,
                        name=self.learn.get_student_name(uid),
                        )


# ----------------------------------------------------------------------------
# Serves files from the /public subdir of the topics.
# ----------------------------------------------------------------------------
class FileHandler(BaseHandler):
    @tornado.web.authenticated
    async def get(self, filename):
        uid = self.current_user
        public_dir = self.learn.get_current_public_dir(uid)
        filepath = path.expanduser(path.join(public_dir, filename))
        content_type = mimetypes.guess_type(filename)[0]

        try:
            f = open(filepath, 'rb')
        except FileNotFoundError:
            logging.error(f'File not found: {filepath}')
        except PermissionError:
            logging.error(f'No permission: {filepath}')
        except Exception as e:
            raise e
        else:
            data = f.read()
            f.close()
            self.set_header("Content-Type", content_type)
            self.write(data)
            await self.flush()


# ----------------------------------------------------------------------------
# respond to AJAX to get a JSON question
# ----------------------------------------------------------------------------
class QuestionHandler(BaseHandler):
    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',
    }

    # --- get question to render
    @tornado.web.authenticated
    def get(self):
        logging.debug('QuestionHandler.get()')
        user = self.current_user
        q = self.learn.get_current_question(user)

        if q is not None:
            qhtml = self.render_string(self.templates[q['type']],
                                       question=q, md=md_to_html)
            response = {
                'method': 'new_question',
                'params': {
                    'type': q['type'],
                    'question': to_unicode(qhtml),
                    'progress': self.learn.get_student_progress(user),
                    'tries': q['tries'],
                    }
                }

        else:
            finished = self.render_string('finished_topic.html')
            response = {
                'method': 'finished_topic',
                'params': {
                    'question': to_unicode(finished)
                    }
                }

        self.write(response)

    # --- post answer, returns what to do next: shake, new_question, finished
    @tornado.web.authenticated
    async def post(self) -> None:
        logging.debug('QuestionHandler.post()')
        user = self.current_user
        answer = self.get_body_arguments('answer')  # list

        # --- check if browser opened different questions simultaneously
        answer_qid = self.get_body_arguments('qid')[0]
        current_qid = self.learn.get_current_question_id(user)
        if answer_qid != current_qid:
            logging.debug(f'User {user} desynchronized questions')
            self.write({
                'method': 'invalid',
                'params': {
                    'msg': ('Esta pergunta já não está activa. '
                            'Tem outra janela aberta?')
                    }
                })
            return

        # --- brain hacking ;)
        await asyncio.sleep(1)

        # --- answers are in a list. fix depending on question type
        qtype = self.learn.get_student_question_type(user)
        if qtype in ('success', 'information', 'info'):
            answer = None
        elif qtype == 'radio' and not answer:
            answer = None
        elif qtype != 'checkbox':   # radio, text, textarea, ...
            answer = answer[0]

        # --- check answer (nonblocking) and get corrected question and action
        q, action = await self.learn.check_answer(user, answer)

        # --- built response to return
        response = {'method': action, 'params': {}}
        if action == 'right':   # get next question in the topic
            comments_html = self.render_string(
                'comments-right.html', comments=q['comments'], md=md_to_html)

            solution_html = self.render_string(
                'solution.html', solution=q['solution'], md=md_to_html)

            response['params'] = {
                'type': q['type'],
                'progress': self.learn.get_student_progress(user),
                'comments': to_unicode(comments_html),
                'solution': to_unicode(solution_html),
                'tries': q['tries'],
                }
        elif action == 'try_again':
            comments_html = self.render_string(
                'comments.html', comments=q['comments'], md=md_to_html)

            response['params'] = {
                'type': q['type'],
                'progress': self.learn.get_student_progress(user),
                'comments': to_unicode(comments_html),
                'tries': q['tries'],
                }
        elif action == 'wrong':  # no more tries
            comments_html = self.render_string(
                'comments.html', comments=q['comments'], md=md_to_html)

            solution_html = self.render_string(
                'solution.html', solution=q['solution'], md=md_to_html)

            response['params'] = {
                'type': q['type'],
                'progress': self.learn.get_student_progress(user),
                'comments': to_unicode(comments_html),
                'solution': to_unicode(solution_html),
                'tries': q['tries'],
                }
        else:
            logging.error(f'Unknown action: {action}')

        self.write(response)


# ----------------------------------------------------------------------------
# Signal handler to catch Ctrl-C and abort server
# ----------------------------------------------------------------------------
def signal_handler(signal, frame):
    r = input(' --> Stop webserver? (yes/no) ').lower()
    if r == 'yes':
        tornado.ioloop.IOLoop.current().stop()
        logging.critical('Webserver stopped.')
        sys.exit(0)
    else:
        logging.info('Abort canceled...')


# ----------------------------------------------------------------------------
def parse_cmdline_arguments():
    argparser = argparse.ArgumentParser(
        description='Server for online learning. Enrolled students and topics '
        'have to be previously configured. Please read the documentation '
        'included with this software before running the server.'
        )

    argparser.add_argument(
        'conffile', type=str, nargs='+',
        help='Topics configuration file in YAML format.'
        )

    argparser.add_argument(
        '--prefix', type=str, default='.',
        help='Path where the topic directories can be found, e.g. ~/topics'
        )

    argparser.add_argument(
        '--port', type=int, default=8443,
        help='Port to be used by the HTTPS server, e.g. 8443'
        )

    argparser.add_argument(
        '--db', type=str, default='students.db',
        help='SQLite3 database file, e.g. students.db'
        )

    argparser.add_argument(
        '--check', action='store_true',
        help='Sanity check all questions'
        )

    argparser.add_argument(
        '--debug', action='store_true',
        help='Enable debug messages'
        )

    return argparser.parse_args()


# ----------------------------------------------------------------------------
def get_logger_config(debug=False):
    if debug:
        filename = 'logger-debug.yaml'
        level = 'DEBUG'
    else:
        filename = 'logger.yaml'
        level = 'INFO'

    config_dir = os.environ.get('XDG_CONFIG_HOME', '~/.config/')
    config_file = path.join(path.expanduser(config_dir), APP_NAME, filename)

    default_config = {
        'version': 1,
        'formatters': {
            'standard': {
                'format': '%(asctime)s %(name)-24s %(levelname)-8s '
                          '%(message)s',
                'datefmt': '%H:%M:%S',
                },
            },
        'handlers': {
            'default': {
                'level': level,
                'class': 'logging.StreamHandler',
                'formatter': 'standard',
                'stream': 'ext://sys.stdout',
                },
            },
        'loggers': {
            '': {  # configuration for serve.py
                'handlers': ['default'],
                'level': level,
                },
            },
        }
    default_config['loggers'].update({
        APP_NAME+'.'+module: {
            'handlers': ['default'],
            'level': level,
            'propagate': False,
            } for module in ['learnapp', 'models', 'factory', 'questions',
                             'knowledge', 'tools']})

    return load_yaml(config_file, default=default_config)


# ----------------------------------------------------------------------------
# Tornado web server
# ----------------------------------------------------------------------------
def main():
    # --- Commandline argument parsing
    arg = parse_cmdline_arguments()

    # --- Setup logging
    logger_config = get_logger_config(arg.debug)
    logging.config.dictConfig(logger_config)

    try:
        logging.config.dictConfig(logger_config)
    except Exception:
        print('An error ocurred while setting up the logging system.')
        sys.exit(1)

    logging.info('====================== Start Logging ======================')

    # --- start application
    logging.info('Starting App...')
    try:
        learnapp = LearnApp(arg.conffile, prefix=arg.prefix, db=arg.db,
                            check=arg.check)
    except Exception:
        logging.critical('Failed to start application.')
        sys.exit(1)

    # --- create web application
    logging.info('Starting Web App (tornado)...')
    try:
        webapp = WebApplication(learnapp, debug=arg.debug)
    except Exception:
        logging.critical('Failed to start web application.')
        sys.exit(1)

    # --- get SSL certificates
    if 'XDG_DATA_HOME' in os.environ:
        certs_dir = path.join(os.environ['XDG_DATA_HOME'], 'certs')
    else:
        certs_dir = path.expanduser('~/.local/share/certs')

    ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
    try:
        ssl_ctx.load_cert_chain(path.join(certs_dir, 'cert.pem'),
                                path.join(certs_dir, 'privkey.pem'))
    except FileNotFoundError:
        logging.critical(f'SSL certificates missing in {certs_dir}')
        sys.exit(1)

    # --- create webserver
    try:
        httpserver = tornado.httpserver.HTTPServer(webapp, ssl_options=ssl_ctx)
    except ValueError:
        logging.critical('Certificates cert.pem and privkey.pem not found')
        sys.exit(1)

    httpserver.listen(arg.port)
    logging.info(f'Listening on port {arg.port}.')

    # --- run webserver
    signal.signal(signal.SIGINT, signal_handler)
    logging.info('Webserver running.  (Ctrl-C to stop)')

    try:
        tornado.ioloop.IOLoop.current().start()  # running...
    except Exception:
        logging.critical('Webserver stopped.')
        tornado.ioloop.IOLoop.current().stop()
        raise


# ----------------------------------------------------------------------------
if __name__ == "__main__":
    main()