serve.py 15 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
#!/usr/bin/env python3

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

# user installed libraries
import tornado.ioloop
import tornado.web
# import tornado.websocket
import tornado.httpserver

# this project
from perguntations.parser_markdown import md_to_html


# ----------------------------------------------------------------------------
# Web Application. Routes to handler classes.
# ----------------------------------------------------------------------------
class WebApplication(tornado.web.Application):
    def __init__(self, testapp, debug=False):
        handlers = [
            (r'/login',         LoginHandler),
            (r'/logout',        LogoutHandler),
            (r'/test',          TestHandler),
            (r'/review',        ReviewHandler),
            (r'/admin',         AdminHandler),
            (r'/file',          FileHandler),
            # (r'/root',      MainHandler), # FIXME
            # (r'/ws',            AdminSocketHandler),
            (r'/',              RootHandler),  # TODO multiple tests
        ]

        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.testapp = testapp


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


# ----------------------------------------------------------------------------
# Base handler. Other handlers will inherit this one.
# ----------------------------------------------------------------------------
class BaseHandler(tornado.web.RequestHandler):
    @property
    def testapp(self):
        return self.application.testapp

    def get_current_user(self):
        cookie = self.get_secure_cookie('user')
        if cookie:
            return cookie.decode('utf-8')


# ----------------------------------------------------------------------------
# class MainHandler(BaseHandler):

#     @tornado.web.authenticated
#     @admin_only
#     def get(self):
#         self.render("admin-ws.html", students=self.testapp.get_students_state())


# # ----------------------------------------------------------------------------
# class AdminSocketHandler(tornado.websocket.WebSocketHandler):
#     waiters = set()
#     # cache = []

#     # def get_compression_options(self):
#     #     return {}   # Non-None enables compression with default options.

#     # called when opening connection
#     def open(self):
#         logging.debug('[AdminSocketHandler.open]')
#         AdminSocketHandler.waiters.add(self)

#     # called when closing connection
#     def on_close(self):
#         logging.debug('[AdminSocketHandler.on_close]')
#         AdminSocketHandler.waiters.remove(self)

#     # @classmethod
#     # def update_cache(cls, chat):
#     #     logging.debug(f'[AdminSocketHandler.update_cache] "{chat}"')
#     #     cls.cache.append(chat)

#     # @classmethod
#     # def send_updates(cls, chat):
#     #     logging.info("sending message to %d waiters", len(cls.waiters))
#     #     for waiter in cls.waiters:
#     #         try:
#     #             waiter.write_message(chat)
#     #         except Exception:
#     #             logging.error("Error sending message", exc_info=True)

#     # handle incomming messages
#     def on_message(self, message):
#         logging.info(f"[AdminSocketHandler.onmessage] got message {message}")
#         parsed = tornado.escape.json_decode(message)
#         print(parsed)
#         chat = {"id": str(uuid.uuid4()), "body": parsed["body"]}
#         print(chat)
#         chat["html"] = tornado.escape.to_basestring(
#             '<div>' + chat['body'] + '</div>'
#             # self.render_string("message.html", message=chat)
#         )
#         print(chat)

#         AdminSocketHandler.update_cache(chat)  # store msgs
#         AdminSocketHandler.send_updates(chat)  # send to clients


# --- ADMIN ------------------------------------------------------------------
class AdminHandler(BaseHandler):
    SUPPORTED_METHODS = ['GET', 'POST']

    @tornado.web.authenticated
    @admin_only
    async def get(self):
        cmd = self.get_query_argument('cmd', default=None)

        if cmd == 'students_table':
            data = {'data': self.testapp.get_students_state()}
            self.write(json.dumps(data, default=str))
        elif cmd == 'test':  # FIXME which test?
            data = {
                'data': {
                    'title': self.testapp.testfactory['title'],
                    'ref': self.testapp.testfactory['ref'],
                    'filename': self.testapp.testfactory['testfile'],
                    'database': self.testapp.testfactory['database'],
                    'answers_dir': self.testapp.testfactory['answers_dir'],
                    }
                }
            self.write(json.dumps(data, default=str))
        else:
            self.render('admin.html')

    @tornado.web.authenticated
    @admin_only
    async def post(self):
        cmd = self.get_body_argument('cmd', None)
        value = self.get_body_argument('value', None)

        if cmd == 'allow':
            self.testapp.allow_student(value)

        elif cmd == 'deny':
            self.testapp.deny_student(value)

        elif cmd == 'reset_password':
            await self.testapp.update_student_password(uid=value, pw='')

        elif cmd == 'insert_student':
            s = json.loads(value)
            self.testapp.insert_new_student(uid=s['number'], name=s['name'])

        else:
            logging.error(f'Unknown command: "{cmd}"')


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

    async def post(self):
        uid = self.get_body_argument('uid').lstrip('l')
        pw = self.get_body_argument('pw')
        login_ok = await self.testapp.login(uid, pw)

        if login_ok:
            self.set_secure_cookie("user", str(uid), expires_days=30)
            self.redirect(self.get_argument("next", "/"))
        else:
            self.render("login.html", error='Não autorizado ou senha inválida')


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

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


# ----------------------------------------------------------------------------
# handles root / to redirect students to /test and admininistrator to /admin
# ----------------------------------------------------------------------------
class RootHandler(BaseHandler):
    @tornado.web.authenticated
    def get(self):
        if self.current_user == '0':
            self.redirect('/admin')
        else:
            self.redirect('/test')


# ----------------------------------------------------------------------------
# Serves files from the /public subdir of the topics.
# ----------------------------------------------------------------------------
class FileHandler(BaseHandler):
    @tornado.web.authenticated
    async def get(self):
        uid = self.current_user
        ref = self.get_query_argument('ref', None)
        image = self.get_query_argument('image', None)
        content_type = mimetypes.guess_type(image)[0]

        if uid != '0':
            t = self.testapp.get_student_test(uid)
        else:
            logging.error('FIXME Cannot serve images for review.')
            raise tornado.web.HTTPError(404)  # FIXME admin

        if t is None:
            raise tornado.web.HTTPError(404)  # Not Found

        for q in t['questions']:
            # search for the question that contains the image
            if q['ref'] == ref:
                filepath = path.join(q['path'], 'public', image)
                try:
                    f = open(filepath, 'rb')
                except FileNotFoundError:
                    logging.error(f'File not found: {filepath}')
                except PermissionError:
                    logging.error(f'No permission: {filepath}')
                except OSError:
                    logging.error(f'Error opening file: {filepath}')
                else:
                    data = f.read()
                    f.close()
                    self.set_header("Content-Type", content_type)
                    self.write(data)
                    await self.flush()
                break  # for loop


# ----------------------------------------------------------------------------
# Test shown to students
# ----------------------------------------------------------------------------
class TestHandler(BaseHandler):
    _templates = {
        'radio':        'question-radio.html',
        'checkbox':     'question-checkbox.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
    @tornado.web.authenticated
    async def get(self):
        uid = self.current_user
        t = self.testapp.get_student_test(uid)  # reloading returns same test
        if t is None:
            t = await self.testapp.generate_test(uid)
        self.render('test.html', t=t, md=md_to_html, templ=self._templates)

    # --- POST
    @tornado.web.authenticated
    async def post(self):
        uid = self.current_user

        # self.request.arguments = {'answered-0': [b'on'], '0': [b'13.45']}
        # build dictionary ans={0: 'answer0', 1:, 'answer1', ...}
        # unanswered questions not included.
        t = self.testapp.get_student_test(uid)
        ans = {}
        for i, q in enumerate(t['questions']):
            qid = str(i)
            if 'answered-' + qid in self.request.arguments:
                ans[i] = self.get_body_arguments(qid)

                # remove enclosing list in some question types
                if q['type'] == 'radio':
                    if not ans[i]:
                        ans[i] = None
                    else:
                        ans[i] = ans[i][0]
                elif q['type'] in ('text', 'text-regex', 'textarea',
                                   'numeric-interval'):
                    ans[i] = ans[i][0]

        # correct answered questions and logout
        await self.testapp.correct_test(uid, ans)
        self.testapp.logout(uid)
        self.clear_cookie('user')

        # show final grade and grades of other tests in the database
        allgrades = self.testapp.get_student_grades_from_all_tests(uid)
        self.render('grade.html', t=t, allgrades=allgrades)


# ----------------------------------------------------------------------------
# FIXME  should be a post in the test with command giveup instead of correct...
# class GiveupHandler(BaseHandler):
#     @tornado.web.authenticated
#     def get(self):
#         uid = self.current_user
#         t = self.testapp.giveup_test(uid)
#         self.testapp.logout(uid)

#         # --- Show result to student
#         self.render('grade.html', t=t, allgrades=self.testapp.get_student_grades_from_all_tests(uid))


# --- REVIEW -----------------------------------------------------------------
class ReviewHandler(BaseHandler):
    SUPPORTED_METHODS = ['GET']

    _templates = {
        'radio':        'review-question-radio.html',
        'checkbox':     'review-question-checkbox.html',
        'text':         'review-question-text.html',
        'text-regex':   'review-question-text.html',
        'numeric-interval': 'review-question-text.html',
        'textarea':     'review-question-text.html',
        # -- information panels --
        'information':  'review-question-information.html',
        'success':      'review-question-information.html',
        'warning':      'review-question-information.html',
        'alert':        'review-question-information.html',
    }

    @tornado.web.authenticated
    @admin_only
    async def get(self):
        test_id = self.get_query_argument('test_id', None)
        logging.info(f'Review test {test_id}.')
        fname = self.testapp.get_json_filename_of_test(test_id)

        if fname is None:
            raise tornado.web.HTTPError(404)  # Not Found

        try:
            f = open(path.expanduser(fname))
        except OSError:
            logging.error(f'Cannot open "{fname}" for review.')
        else:
            with f:
                t = json.load(f)
            self.render('review.html', t=t, md=md_to_html,
                        templ=self._templates)



# ----------------------------------------------------------------------------
def signal_handler(signal, frame):
    r = input(' --> Stop webserver? (yes/no) ')
    if r.lower() == 'yes':
        tornado.ioloop.IOLoop.current().stop()
        logging.critical('Webserver stopped.')
        sys.exit(0)

# ----------------------------------------------------------------------------
def run_webserver(app, ssl, port, debug):
    # --- create web application ---------------------------------------------
    logging.info('Starting WebApplication (tornado)')
    try:
        webapp = WebApplication(app, debug=debug)
    except Exception:
        logging.critical('Failed to start web application.')
        raise

    try:
        httpserver = tornado.httpserver.HTTPServer(webapp, ssl_options=ssl)
    except ValueError:
        logging.critical('Certificates cert.pem, privkey.pem not found')
        sys.exit(1)

    try:
        httpserver.listen(port)
    except OSError:
        logger.critical(f'Cannot bind port {port}. Already in use?')
        sys.exit(1)

    logging.info(f'Webserver listening on {port}...  (Ctrl-C to stop)')
    signal.signal(signal.SIGINT, signal_handler)

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