forked from hedyorg/hedy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
1860 lines (1483 loc) · 70.8 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
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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf-8
import sys
from website.yaml_file import YamlFile
if (sys.version_info.major < 3 or sys.version_info.minor < 7):
print('Hedy requires Python 3.7 or newer to run. However, your version of Python is',
'.'.join([str(sys.version_info.major), str(sys.version_info.minor), str(sys.version_info.micro)]))
quit()
import datetime
import collections
import hedy
import json
import logging
import os
from os import path
import re
import traceback
import uuid
from ruamel import yaml
from flask_commonmark import Commonmark
from werkzeug.urls import url_encode
from config import config
from website.auth import auth_templates, current_user, login_user_from_token_cookie, requires_login, is_admin, \
is_teacher, update_is_teacher, pick
from utils import timems, load_yaml_rt, dump_yaml_rt, version, is_debug_mode
import utils
import textwrap
# app.py
from flask import Flask, request, jsonify, session, abort, g, redirect, Response, make_response, url_for, Markup
from flask_helpers import render_template
from flask_compress import Compress
# Hedy-specific modules
import hedy_content
import hedyweb
from website import querylog, aws_helpers, jsonbin, translating, ab_proxying, cdn, database, achievements, quiz_svg_icons
from website.log_fetcher import log_fetcher
import quiz
# Set the current directory to the root Hedy folder
os.chdir(os.path.join(os.getcwd(), __file__.replace(os.path.basename(__file__), '')))
# Define and load all available language data
ALL_LANGUAGES = {
'en': 'English',
'nl': 'Nederlands',
'es': 'Español',
'fr': 'Français',
'pt_pt': 'Português(pt)',
'pt_br': 'Português(br)',
'de': 'Deutsch',
'it': 'Italiano',
'sw': 'Swahili',
'hu': 'Magyar',
'el': 'Ελληνικά',
'zh': "简体中文",
'cs': 'Čeština',
'bg': 'Български',
'bn': 'বাংলা',
'hi': 'हिंदी',
'id': 'Bahasa Indonesia',
'fy': 'Frysk',
'ar': 'عربى'
}
# Define fall back languages for adventures
FALL_BACK_ADVENTURE = {
'fy': 'nl',
'pt_br': 'pt_pt'
}
LEVEL_DEFAULTS = collections.defaultdict(hedy_content.NoSuchDefaults)
for lang in ALL_LANGUAGES.keys():
LEVEL_DEFAULTS[lang] = hedy_content.LevelDefaults(lang)
ADVENTURES = collections.defaultdict(hedy_content.NoSuchAdventure)
for lang in ALL_LANGUAGES.keys():
ADVENTURES[lang] = hedy_content.Adventures(lang)
TRANSLATIONS = hedyweb.Translations()
ACHIEVEMENTS_TRANSLATIONS = hedyweb.AchievementTranslations()
ACHIEVEMENTS = achievements.Achievements()
DATABASE = database.Database()
# Define code that will be used if some turtle command is present
TURTLE_PREFIX_CODE = textwrap.dedent("""\
# coding=utf8
import random, time, turtle
t = turtle.Turtle()
t.hideturtle()
t.speed(0)
t.penup()
t.goto(50,100)
t.showturtle()
t.pendown()
t.speed(3)
""")
# Preamble that will be used for non-Turtle programs
NORMAL_PREFIX_CODE = textwrap.dedent("""\
# coding=utf8
import random, time
""")
def load_adventure_for_language(lang):
adventures_for_lang = ADVENTURES[lang]
if not adventures_for_lang.has_adventures():
# The default fall back language is English
fall_back = FALL_BACK_ADVENTURE.get(lang, "en")
adventures_for_lang = ADVENTURES[fall_back]
return adventures_for_lang.adventures_file['adventures']
def load_adventures_per_level(lang, level):
loaded_programs = {}
# If user is logged in, we iterate their programs that belong to the current level. Out of these, we keep the latest created program for both the level mode(no adventure) and for each of the adventures.
if current_user()['username']:
user_programs = DATABASE.programs_for_user(current_user()['username'])
for program in user_programs:
if program['level'] != level:
continue
program_key = 'level' if not program.get('adventure_name') else program['adventure_name']
if not program_key in loaded_programs:
loaded_programs[program_key] = program
elif loaded_programs[program_key]['date'] < program['date']:
loaded_programs[program_key] = program
all_adventures = []
adventures = load_adventure_for_language(lang)
for short_name, adventure in adventures.items():
if not level in adventure['levels']:
continue
# end adventure is the quiz
# if quizzes are not enabled, do not load it
if short_name == 'end' and not config['quiz-enabled']:
continue
current_adventure = {
'short_name': short_name,
'name': adventure['name'],
'image': adventure.get('image', None),
'default_save_name': adventure['default_save_name'],
'text': adventure['levels'][level].get('story_text', 'No Story Text'),
'example_code': adventure['levels'][level].get('example_code'),
'start_code': adventure['levels'][level].get('start_code', ''),
'loaded_program': '' if not loaded_programs.get(short_name) else {
'name': loaded_programs.get(short_name)['name'],
'code': loaded_programs.get(short_name)['code']
}
}
#Sometimes we have multiple text and example_code -> iterate these and add as well!
extra_stories = []
for i in range(2, 10):
extra_story = {}
if adventure['levels'][level].get('story_text_' + str(i)):
extra_story['text'] = adventure['levels'][level].get('story_text_' + str(i))
if adventure['levels'][level].get('example_code_' + str(i)):
extra_story['example_code'] = adventure['levels'][level].get('example_code_' + str(i))
extra_stories.append(extra_story)
else:
break
current_adventure['extra_stories'] = extra_stories
all_adventures.append(current_adventure)
# We create a 'level' pseudo assignment to store the loaded program for level mode, if any.
all_adventures.append({
'short_name': 'level',
'loaded_program': '' if not loaded_programs.get('level') else {
'name': loaded_programs.get('level')['name'],
'code': loaded_programs.get('level')['code']
}
})
return all_adventures
# Load main menu(do it once, can be cached)
with open(f'menu.json', 'r', encoding='utf-8') as f:
main_menu_json = json.load(f)
logging.basicConfig(
level=logging.DEBUG,
format='[%(asctime)s] %(levelname)-8s: %(message)s')
app = Flask(__name__, static_url_path='')
# Ignore trailing slashes in URLs
app.url_map.strict_slashes = False
cdn.Cdn(app, os.getenv('CDN_PREFIX'), os.getenv('HEROKU_SLUG_COMMIT', 'dev'))
@app.before_request
def before_request_begin_logging():
"""Initialize the query logging.
This needs to happen as one of the first things, as the database calls
etc. depend on it.
"""
path = (str(request.path) + '?' + str(request.query_string)) if request.query_string else str(request.path)
querylog.begin_global_log_record(path=path, method=request.method)
@app.after_request
def after_request_log_status(response):
querylog.log_value(http_code=response.status_code)
return response
@app.before_request
def initialize_session():
"""Make sure the session is initialized.
- Each session gets a unique session ID, so we can tell user sessions apart
and know what programs get submitted after each other.
- If the user has a cookie with a long-lived login token, log them in from
that cookie (copy the user info into the session for efficient access
later on).
"""
# Invoke session_id() for its side effect
session_id()
login_user_from_token_cookie()
if os.getenv('IS_PRODUCTION'):
@app.before_request
def reject_e2e_requests():
if utils.is_testing_request(request):
return 'No E2E tests are allowed in production', 400
@app.before_request
def before_request_proxy_testing():
if utils.is_testing_request(request):
if os.getenv('IS_TEST_ENV'):
session['test_session'] = 'test'
# HTTP -> HTTPS redirect
# https://stackoverflow.com/questions/32237379/python-flask-redirect-to-https-from-http/32238093
if os.getenv('REDIRECT_HTTP_TO_HTTPS'):
@app.before_request
def before_request_https():
if request.url.startswith('http://'):
url = request.url.replace('http://', 'https://', 1)
# We use a 302 in case we need to revert the redirect.
return redirect(url, code=302)
# Unique random key for sessions.
# For settings with multiple workers, an environment variable is required, otherwise cookies will be constantly removed and re-set by different workers.
if utils.is_production():
if not os.getenv('SECRET_KEY'):
raise RuntimeError('The SECRET KEY must be provided for non-dev environments.')
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY')
else:
# The value doesn't matter for dev environments, but it needs to be a constant
# so that our cookies don't get invalidated every time we restart the server.
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'WeAreDeveloping')
if utils.is_heroku():
app.config.update(
SESSION_COOKIE_SECURE=True,
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SAMESITE='Lax',
)
# Set security attributes for cookies in a central place - but not when running locally, so that session cookies work well without HTTPS
Compress(app)
Commonmark(app)
parse_logger = jsonbin.MultiParseLogger(
jsonbin.JsonBinLogger.from_env_vars(),
jsonbin.S3ParseLogger.from_env_vars())
querylog.LOG_QUEUE.set_transmitter(aws_helpers.s3_querylog_transmitter_from_env())
@app.before_request
def setup_language():
# Determine the user's requested language code.
#
# If not in the request parameters, use the browser's accept-languages
# header to do language negotiation.
if 'lang' not in session:
session['lang'] = request.accept_languages.best_match(ALL_LANGUAGES.keys(), 'en')
g.lang = session['lang']
# Set the page direction -> automatically set it to "left-to-right"
# Switch to "right-to-left" if one of the language in the list is selected
# This is the only place to expand / shrink the list of RTL languages -> front-end is fixed based on this value
g.dir = "ltr"
if g.lang in ['ar', 'he', 'ur']:
g.dir = "rtl"
# Check that requested language is supported, otherwise return 404
if g.lang not in ALL_LANGUAGES.keys():
return "Language " + g.lang + " not supported", 404
# Also get the 'ui' translations into a global object for this language, these
# are used a lot so we can clean up a fair bit by initializing here.
g.ui_texts = TRANSLATIONS.get_translations(g.lang, 'ui')
g.auth_texts = TRANSLATIONS.get_translations(g.lang, 'Auth')
if utils.is_heroku() and not os.getenv('HEROKU_RELEASE_CREATED_AT'):
logging.warning(
'Cannot determine release; enable Dyno metadata by running "heroku labs:enable runtime-dyno-metadata -a <APP_NAME>"')
# A context processor injects variables in the context that are available to all templates.
@app.context_processor
def enrich_context_with_user_info():
user = current_user()
data = {'username': user.get('username', ''), 'is_teacher': is_teacher(user), 'is_admin': is_admin(user)}
if len(data['username']) > 0: #If so, there is a user -> Retrieve all relevant info
user_data = DATABASE.user_by_username(user.get('username'))
data['user_messages'] = 0
if 'language' in user_data:
if user_data['language'] in ALL_LANGUAGES.keys():
g.lang = session['lang'] = user_data['language']
data['user_data'] = user_data
if 'classes' in user_data:
data['user_classes'] = DATABASE.get_student_classes(user.get('username'))
user_achievements = DATABASE.achievements_by_username(user.get('username'))
if user_achievements:
data['user_achievements'] = user_achievements
user_invites = DATABASE.get_username_invite(user.get('username'))
if user_invites:
Class = DATABASE.get_class(user_invites['class_id'])
if Class:
invite_data = user_invites.copy()
invite_data['class_name'] = Class.get('name')
invite_data['teacher'] = Class.get('teacher')
invite_data['join_link'] = Class.get('link')
data['invite_data'] = invite_data
data['user_messages'] += 1
return data
@app.context_processor
def enricht_context_with_translations():
"""Adds dicts with translations to the global template context.
For some reason these are held in various different sections in the YAMLs.
"""
texts = TRANSLATIONS.get_translations(g.lang, 'Programs')
ui = TRANSLATIONS.get_translations(g.lang, 'ui')
auth = TRANSLATIONS.get_translations(g.lang, 'Auth')
achievements = ACHIEVEMENTS_TRANSLATIONS.get_translations(g.lang)
return dict(texts=texts, ui=ui, auth=auth, achievements=achievements)
@app.after_request
def set_security_headers(response):
security_headers = {
'Strict-Transport-Security': 'max-age=31536000; includeSubDomains',
'X-XSS-Protection': '1; mode=block',
}
# Not X-Frame-Options on purpose -- we are being embedded by Online Masters
# and that's okay.
response.headers.update(security_headers)
return response
@app.teardown_request
def teardown_request_finish_logging(exc):
querylog.finish_global_log_record(exc)
# If present, PROXY_TO_TEST_HOST should be the 'http[s]://hostname[:port]' of the target environment
if os.getenv('PROXY_TO_TEST_HOST') and not os.getenv('IS_TEST_ENV'):
ab_proxying.ABProxying(app, os.getenv('PROXY_TO_TEST_HOST'), app.config['SECRET_KEY'])
@app.route('/session_test', methods=['GET'])
def echo_session_vars_test():
if not utils.is_testing_request(request):
return 'This endpoint is only meant for E2E tests', 400
return jsonify({'session': dict(session)})
@app.route('/session_main', methods=['GET'])
def echo_session_vars_main():
if not utils.is_testing_request(request):
return 'This endpoint is only meant for E2E tests', 400
return jsonify({'session': dict(session), 'proxy_enabled': bool(os.getenv('PROXY_TO_TEST_HOST'))})
@app.route('/fix-code', methods=['POST'])
def fix_code():
body = request.json
if not body:
return "body must be an object", 400
if 'code' not in body:
return "body.code must be a string", 400
if 'level' not in body:
return "body.level must be a string", 400
if 'adventure_name' in body and not isinstance(body['adventure_name'], str):
return "if present, body.adventure_name must be a string", 400
code = body['code']
level = int(body['level'])
# Language should come principally from the request body,
# but we'll fall back to browser default if it's missing for whatever
# reason.
lang = body.get('lang', g.lang)
# true if kid enabled the read aloud option
read_aloud = body.get('read_aloud', False)
response = {}
username = current_user()['username'] or None
exception = None
querylog.log_value(level=level, lang=lang, session_id=session_id(), username=username)
try:
hedy_errors = TRANSLATIONS.get_translations(lang, 'HedyErrorMessages')
with querylog.log_time('transpile'):
try:
transpile_result = hedy.transpile(code, level)
response = "OK"
except hedy.exceptions.FtfyException as ex:
# The code was fixed with a warning
response['Error'] = translate_error(ex.error_code, hedy_errors, ex.arguments)
response['FixedCode'] = ex.fixed_code
response['Location'] = ex.error_location
transpile_result = ex.fixed_result
exception = ex
except hedy.exceptions.HedyException as ex:
traceback.print_exc()
response = hedy_error_to_response(ex, hedy_errors)
exception = ex
except Exception as E:
traceback.print_exc()
print(f"error transpiling {code}")
response["Error"] = str(E)
exception = ex
querylog.log_value(server_error=response.get('Error'))
parse_logger.log({
'session': session_id(),
'date': str(datetime.datetime.now()),
'level': level,
'lang': lang,
'code': code,
'server_error': response.get('Error'),
'exception': get_class_name(exception),
'version': version(),
'username': username,
'read_aloud': read_aloud,
'is_test': 1 if os.getenv('IS_TEST_ENV') else None,
'adventure_name': body.get('adventure_name', None)
})
return jsonify(response)
@app.route('/parse', methods=['POST'])
def parse():
body = request.json
if not body:
return "body must be an object", 400
if 'code' not in body:
return "body.code must be a string", 400
if 'level' not in body:
return "body.level must be a string", 400
if 'adventure_name' in body and not isinstance(body['adventure_name'], str):
return "if present, body.adventure_name must be a string", 400
code = body['code']
level = int(body['level'])
# Language should come principally from the request body,
# but we'll fall back to browser default if it's missing for whatever
# reason.
lang = body.get('lang', g.lang)
# true if kid enabled the read aloud option
read_aloud = body.get('read_aloud', False)
response = {}
username = current_user()['username'] or None
exception = None
querylog.log_value(level=level, lang=lang, session_id=session_id(), username=username)
try:
hedy_errors = TRANSLATIONS.get_translations(lang, 'HedyErrorMessages')
with querylog.log_time('transpile'):
try:
transpile_result = transpile_add_stats(code, level, lang)
if username:
DATABASE.increase_user_run_count(username)
ACHIEVEMENTS.increase_count("run")
except hedy.exceptions.InvalidSpaceException as ex:
response['Warning'] = translate_error(ex.error_code, hedy_errors, ex.arguments)
response['Location'] = ex.error_location
transpile_result = ex.fixed_result
exception = ex
except hedy.exceptions.InvalidCommandException as ex:
response['Error'] = translate_error(ex.error_code, hedy_errors, ex.arguments)
response['Location'] = ex.error_location
transpile_result = ex.fixed_result
exception = ex
except hedy.exceptions.FtfyException as ex:
response['Error'] = translate_error(ex.error_code, hedy_errors, ex.arguments)
response['Location'] = ex.error_location
transpile_result = ex.fixed_result
exception = ex
try:
if transpile_result.has_turtle:
response['Code'] = TURTLE_PREFIX_CODE + transpile_result.code
response['has_turtle'] = True
else:
response['Code'] = NORMAL_PREFIX_CODE + transpile_result.code
except:
pass
try:
if 'sleep' in hedy.all_commands(code, level, lang):
response['has_sleep'] = True
except:
pass
try:
if username and ACHIEVEMENTS.verify_run_achievements(username, code, level, response):
response['achievements'] = ACHIEVEMENTS.get_earned_achievements()
except Exception as E:
print(f"error determining achievements for {code} with {E}")
except hedy.exceptions.HedyException as ex:
traceback.print_exc()
response = hedy_error_to_response(ex, hedy_errors)
exception = ex
except Exception as E:
traceback.print_exc()
print(f"error transpiling {code}")
response["Error"] = str(E)
exception = E
querylog.log_value(server_error=response.get('Error'))
parse_logger.log({
'session': session_id(),
'date': str(datetime.datetime.now()),
'level': level,
'lang': lang,
'code': code,
'server_error': response.get('Error'),
'exception': get_class_name(exception),
'version': version(),
'username': username,
'read_aloud': read_aloud,
'is_test': 1 if os.getenv('IS_TEST_ENV') else None,
'adventure_name': body.get('adventure_name', None)
})
return jsonify(response)
def transpile_add_stats(code, level, lang_):
username = current_user()['username'] or None
try:
result = hedy.transpile(code, level, lang_)
add_program_stats(username, level)
return result
except Exception as ex:
add_program_stats(username, level, get_class_name(ex))
raise
def get_class_name(i):
if i is not None:
return str(i.__class__.__name__)
return i
def add_program_stats(username, level, ex=None):
try:
DATABASE.add_program_stats('@all', level, ex)
if username:
DATABASE.add_program_stats(username, level, ex)
except Exception as ex:
# Adding stats should not cause failure. Log and continue.
querylog.log_value(server_error=ex)
def hedy_error_to_response(ex, translations):
return {
"Error": translate_error(ex.error_code, translations, ex.arguments),
"Location": ex.error_location
}
def translate_error(code, translations, arguments):
arguments_that_require_translation = ['allowed_types', 'invalid_type', 'invalid_type_2', 'character_found',
'concept', 'tip']
arguments_that_require_highlighting = ['command', 'guessed_command', 'invalid_argument', 'invalid_argument_2',
'variable']
# fetch the error template
error_template = translations[code]
# some arguments like allowed types or characters need to be translated in the error message
for k, v in arguments.items():
if k in arguments_that_require_highlighting:
arguments[k] = hedy.style_closest_command(v)
if k in arguments_that_require_translation:
if isinstance(v, list):
arguments[k] = translate_list(translations, v)
else:
arguments[k] = translations.get(v, v)
return error_template.format(**arguments)
def translate_list(translations, args):
translated_args = [translations.get(a, a) for a in args]
# Deduplication is needed because diff values could be translated to the same value, e.g. int and float => a number
translated_args = list(dict.fromkeys(translated_args))
if len(translated_args) > 1:
return f"{', '.join(translated_args[0:-1])}" \
f" {translations.get('or', 'or')} " \
f"{translated_args[-1]}"
return ''.join(translated_args)
@app.route('/report_error', methods=['POST'])
def report_error():
post_body = request.json
parse_logger.log({
'session': session_id(),
'date': str(datetime.datetime.now()),
'level': post_body.get('level'),
'code': post_body.get('code'),
'client_error': post_body.get('client_error'),
'version': version(),
'username': current_user()['username'] or None,
'is_test': 1 if os.getenv('IS_TEST_ENV') else None
})
return 'logged'
@app.route('/client_exception', methods=['POST'])
def report_client_exception():
post_body = request.json
querylog.log_value(
session=session_id(),
date=str(datetime.datetime.now()),
client_error=post_body,
version=version(),
username=current_user()['username'] or None,
is_test=1 if os.getenv('IS_TEST_ENV') else None
)
# Return a 500 so the HTTP status codes will stand out in our monitoring/logging
return 'logged', 500
@app.route('/version', methods=['GET'])
def version_page():
"""
Generate a page with some diagnostic information and a useful GitHub URL on upcoming changes.
This is an admin-only page, it does not need to be linked.
(Also does not have any sensitive information so it's fine to be unauthenticated).
"""
app_name = os.getenv('HEROKU_APP_NAME')
vrz = os.getenv('HEROKU_RELEASE_CREATED_AT')
the_date = datetime.date.fromisoformat(vrz[:10]) if vrz else datetime.date.today()
commit = os.getenv('HEROKU_SLUG_COMMIT', '????')[0:6]
return render_template('version-page.html',
app_name=app_name,
heroku_release_time=the_date,
commit=commit)
def achievements_page():
user = current_user()
username = user['username']
if not username:
# redirect users to /login if they are not logged in
url = request.url.replace('/my-achievements', '/login')
return redirect(url, code=302)
achievement_translations = hedyweb.PageTranslations('achievements').get_page_translations(g.lang)
return render_template('achievements.html', page_title=hedyweb.get_page_title('achievements'),
template_achievements=achievement_translations, current_page='my-profile')
@app.route('/programs', methods=['GET'])
@requires_login
def programs_page(user):
username = user['username']
if not username:
# redirect users to /login if they are not logged in
url = request.url.replace('/programs', '/login')
return redirect(url, code=302)
from_user = request.args.get('user') or None
# If from_user -> A teacher is trying to view the user programs
if from_user and not is_admin(user):
if not is_teacher(user):
return utils.error_page(error=403, ui_message='not_teacher')
students = DATABASE.get_teacher_students(username)
if from_user not in students:
return utils.error_page(error=403, ui_message='not_enrolled')
adventures = load_adventure_for_language(g.lang)
if hedy_content.Adventures(session['lang']).has_adventures():
adventures_names = hedy_content.Adventures(session['lang']).get_adventure_keyname_name_levels()
else:
adventures_names = hedy_content.Adventures("en").get_adventure_keyname_name_levels()
# We request our own page -> also get the public_profile settings
public_profile = None
if not from_user:
public_profile = DATABASE.get_public_profile_settings(username)
level = request.args.get('level', default=None, type=str)
adventure = request.args.get('adventure', default=None, type=str)
level = None if level == "null" else level
adventure = None if adventure == "null" else adventure
if level or adventure:
result = DATABASE.filtered_programs_for_user(from_user or username, level, adventure)
else:
result = DATABASE.programs_for_user(from_user or username)
programs = []
now = timems()
for item in result:
date = get_user_formatted_age(now, item['date'])
programs.append(
{'id': item['id'], 'code': item['code'], 'date': date, 'level': item['level'], 'name': item['name'],
'adventure_name': item.get('adventure_name'), 'submitted': item.get('submitted'),
'public': item.get('public')})
return render_template('programs.html', programs=programs, page_title=hedyweb.get_page_title('programs'),
current_page='programs', from_user=from_user, adventures=adventures,
filtered_level=level, filtered_adventure=adventure, adventure_names=adventures_names,
public_profile=public_profile, max_level=hedy.HEDY_MAX_LEVEL)
@app.route('/logs/query', methods=['POST'])
def query_logs():
user = current_user()
if not is_admin(user) and not is_teacher(user):
return 'unauthorized', 403
body = request.json
if body is not None and not isinstance(body, dict):
return 'body must be an object', 400
class_id = body.get('class_id')
if not is_admin(user):
username_filter = body.get('username')
if not class_id or not username_filter:
return 'unauthorized', 403
class_ = DATABASE.get_class(class_id)
if not class_ or class_['teacher'] != user['username'] or username_filter not in class_.get('students', []):
return 'unauthorized', 403
(exec_id, status) = log_fetcher.query(body)
response = {'query_status': status, 'query_execution_id': exec_id}
return jsonify(response)
@app.route('/logs/results', methods=['GET'])
def get_log_results():
query_execution_id = request.args.get('query_execution_id', default=None, type=str)
next_token = request.args.get('next_token', default=None, type=str)
user = current_user()
if not is_admin(user) and not is_teacher(user):
return 'unauthorized', 403
data, next_token = log_fetcher.get_query_results(query_execution_id, next_token)
response = {'data': data, 'next_token': next_token}
return jsonify(response)
def get_user_formatted_age(now, date):
texts = TRANSLATIONS.get_translations(g.lang, 'Programs')
program_age = now - date
if program_age < 1000 * 60 * 60:
measure = texts['minutes']
date = round(program_age / (1000 * 60))
elif program_age < 1000 * 60 * 60 * 24:
measure = texts['hours']
date = round(program_age / (1000 * 60 * 60))
else:
measure = texts['days']
date = round(program_age / (1000 * 60 * 60 * 24))
return f"{texts['ago-1']} {date} {measure} {texts['ago-2']}"
@app.route('/quiz/start/<int:level>', methods=['GET'])
def get_quiz_start(level):
if not is_quiz_enabled():
return quiz_disabled_error()
g.prefix = '/hedy'
# A unique identifier to record the answers under
session['quiz-attempt-id'] = uuid.uuid4().hex
# Sets the values of total_score and correct on the beginning of the quiz at 0
session['total_score'] = 0
session['correct_answer'] = 0
return render_template('startquiz.html', level=level, next_assignment=1)
# Quiz mode
# Fill in the filename as source
@app.route('/quiz/quiz_questions/<int:level_source>/<int:question_nr>', methods=['GET'], defaults={'attempt': 1})
@app.route('/quiz/quiz_questions/<int:level_source>/<int:question_nr>/<int:attempt>', methods=['GET'])
def get_quiz(level_source, question_nr, attempt):
if not is_quiz_enabled():
return quiz_disabled_error()
# If we don't have an attempt ID yet, redirect to the start page
if not session.get('quiz-attempt-id'):
return redirect(url_for('get_quiz_start', level=level_source, lang=g.lang))
# Reading the yaml file
questions = quiz.quiz_data_file_for(g.lang, level_source)
if not questions:
return no_quiz_data_error()
# set globals
g.prefix = '/hedy'
question_status = 'start' if attempt == 1 else 'false'
if question_nr > quiz.highest_question(questions):
return redirect(url_for('quiz_finished', level=level_source, lang=g.lang))
question = quiz.get_question(questions, question_nr)
question_obj = quiz.question_options_for(question)
# Read from session. Don't remove yet: If the user refreshes the
# page here, we want to keep this same information in place (otherwise
# if we removed from the session here it would be gone on page refresh).
chosen_option = session.get('chosenOption', None)
wrong_answer_hint = session.get('wrong_answer_hint', None)
# Store the answer in the database. If we don't have a username,
# use the session ID as a username.
username = current_user()['username'] or f'anonymous:{session_id()}'
if attempt == 1:
is_correct = quiz.is_correct_answer(question, chosen_option)
# the answer is not yet answered so is_correct is None
DATABASE.record_quiz_answer(session['quiz-attempt-id'],
username=username,
level=level_source,
is_correct=is_correct,
question_number=question_nr,
answer=None)
quiz_answers = DATABASE.get_quiz_answer(username, level_source, session['quiz-attempt-id'])
return render_template('quiz_question.html',
level_source=level_source,
quiz_answers = quiz_answers,
questionStatus=question_status,
questions=questions,
question_options=question_obj,
chosen_option=chosen_option,
wrong_answer_hint=wrong_answer_hint,
question=question,
question_nr=question_nr,
correct=session.get('correct_answer'),
attempt=attempt,
is_last_attempt=attempt == quiz.MAX_ATTEMPTS,
lang=g.lang,
cross=quiz_svg_icons.icons['cross'],
check=quiz_svg_icons.icons['check'],
triangle = quiz_svg_icons.icons['triangle'],
diamond = quiz_svg_icons.icons['diamond'],
square = quiz_svg_icons.icons['square'],
circle = quiz_svg_icons.icons['circle'],
pentagram = quiz_svg_icons.icons['pentagram'],
triangle_6 = quiz_svg_icons.icons['triangle_6'])
@app.route('/quiz/finished/<int:level>', methods=['GET'])
def quiz_finished(level):
"""Results page at the end of the quiz."""
if not is_quiz_enabled():
return quiz_disabled_error()
# Reading the yaml file
questions = quiz.quiz_data_file_for(g.lang, level)
if not questions:
return no_quiz_data_error()
# set globals
g.prefix = '/hedy'
achievement = None
if current_user()['username']:
achievement = ACHIEVEMENTS.add_single_achievement(current_user()['username'], "next_question")
if round(session.get('total_score', 0) / quiz.max_score(questions) * 100) == 100:
if achievement:
achievement.append(ACHIEVEMENTS.add_single_achievement(current_user()['username'], "quiz_master")[0])
else:
achievement = ACHIEVEMENTS.add_single_achievement(current_user()['username'], "quiz_master")
if achievement:
achievement = json.dumps(achievement)
print(achievement)
# use the session ID as a username.
username = current_user()['username'] or f'anonymous:{session_id()}'
return render_template('endquiz.html', correct=session.get('correct_answer', 0),
total_score=round(session.get('total_score', 0) / quiz.max_score(questions) * 100),
level_source=level,
achievement=achievement,
level=int(level) + 1,
questions=questions,
next_assignment=1,
cross = quiz_svg_icons.icons['cross'],
check = quiz_svg_icons.icons['check'],
)
@app.route('/quiz/submit_answer/<int:level_source>/<int:question_nr>/<int:attempt>', methods=["POST"])
def submit_answer(level_source, question_nr, attempt):
if not is_quiz_enabled():
return quiz_disabled_error()
# If we don't have an attempt ID yet, redirect to the start page
if not session.get('quiz-attempt-id'):
return redirect(url_for('get_quiz_start', level=level_source, lang=g.lang))
# Get the chosen option from the request form with radio buttons
# This looks like '1-B' or '5-C' or what have you.
#
# The number should always be the same as 'question_nr', or otherwise
# be 'question_nr - 1', so is unnecessary. But we'll leave it here for now.
if request.method == "POST":
# The value is a character and not a text
chosen_option = request.form.get("submit-button")
print('-----------------chosen option', chosen_option)
# Reading the yaml file
questions = quiz.quiz_data_file_for(g.lang, level_source)
if not questions:
return no_quiz_data_error()
# Convert question_nr to an integer
q_nr = int(question_nr)
# Convert the corresponding chosen option to the index of an option
question = quiz.get_question(questions, q_nr)
is_correct = quiz.is_correct_answer(question, chosen_option)
session['chosenOption'] = chosen_option
if not is_correct:
session['wrong_answer_hint'] = quiz.get_hint(question, chosen_option)
else:
# Correct answer -- make sure there is no hint on the next display page
session.pop('wrong_answer_hint', None)
# Store the answer in the database. If we don't have a username,
# use the session ID as a username.
username = current_user()['username'] or f'anonymous:{session_id()}'
DATABASE.record_quiz_answer(session['quiz-attempt-id'],
username=username,
level=level_source,
is_correct=is_correct,
question_number=question_nr,
answer=chosen_option)
if is_correct:
score = quiz.correct_answer_score(question)
session['total_score'] = session.get('total_score', 0) + score
session['correct_answer'] = session.get('correct_answer', 0) + 1
quiz_answers = DATABASE.get_quiz_answer(username, level_source, session['quiz-attempt-id'])
return redirect(url_for('quiz_feedback', quiz_answers= quiz_answers, level_source=level_source, question_nr=question_nr, lang=g.lang))
# Not a correct answer. You can try again if you haven't hit your max attempts yet.
if attempt >= quiz.MAX_ATTEMPTS:
quiz_answers = DATABASE.get_quiz_answer(username, level_source, session['quiz-attempt-id'])