forked from hedyorg/hedy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
1462 lines (1169 loc) · 58.2 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
import hedy_translation
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
from flask_commonmark import Commonmark
from werkzeug.urls import url_encode
from config import config
from website.auth import current_user, login_user_from_token_cookie, requires_login, is_admin, is_teacher, update_is_teacher
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, Markup
from flask_helpers import render_template
from flask_compress import Compress
from flask_babel import Babel, refresh
from flask_babel import gettext
# Hedy-specific modules
import hedy_content
import hedyweb
from hedy_content import ALL_LANGUAGES, FALL_BACK_ADVENTURE, ALL_KEYWORD_LANGUAGES
from website import querylog, aws_helpers, jsonbin, translating, ab_proxying, cdn, database, achievements
from website.log_fetcher import log_fetcher
# Set the current directory to the root Hedy folder
os.chdir(os.path.join(os.getcwd(), __file__.replace(os.path.basename(__file__), '')))
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)
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
# numerals list generated from: https://replit.com/@mevrHermans/multilangnumerals
NORMAL_PREFIX_CODE = textwrap.dedent("""\
# coding=utf8
import random, time
global int_saver
int_saver = int
def int(s):
if isinstance(s, str):
numerals_dict = {'0': '0', '1': '1', '2': '2', '3': '3', '4': '4', '5': '5', '6': '6', '7': '7', '8': '8', '9': '9', '𑁦': '0', '𑁧': '1', '𑁨': '2', '𑁩': '3', '𑁪': '4', '𑁫': '5', '𑁬': '6', '𑁭': '7', '𑁮': '8', '𑁯': '9', '०': '0', '१': '1', '२': '2', '३': '3', '४': '4', '५': '5', '६': '6', '७': '7', '८': '8', '९': '9', '૦': '0', '૧': '1', '૨': '2', '૩': '3', '૪': '4', '૫': '5', '૬': '6', '૭': '7', '૮': '8', '૯': '9', '੦': '0', '੧': '1', '੨': '2', '੩': '3', '੪': '4', '੫': '5', '੬': '6', '੭': '7', '੮': '8', '੯': '9', '০': '0', '১': '1', '২': '2', '৩': '3', '৪': '4', '৫': '5', '৬': '6', '৭': '7', '৮': '8', '৯': '9', '೦': '0', '೧': '1', '೨': '2', '೩': '3', '೪': '4', '೫': '5', '೬': '6', '೭': '7', '೮': '8', '೯': '9', '୦': '0', '୧': '1', '୨': '2', '୩': '3', '୪': '4', '୫': '5', '୬': '6', '୭': '7', '୮': '8', '୯': '9', '൦': '0', '൧': '1', '൨': '2', '൩': '3', '൪': '4', '൫': '5', '൬': '6', '൭': '7', '൮': '8', '൯': '9', '௦': '0', '௧': '1', '௨': '2', '௩': '3', '௪': '4', '௫': '5', '௬': '6', '௭': '7', '௮': '8', '௯': '9', '౦': '0', '౧': '1', '౨': '2', '౩': '3', '౪': '4', '౫': '5', '౬': '6', '౭': '7', '౮': '8', '౯': '9', '၀': '0', '၁': '1', '၂': '2', '၃': '3', '၄': '4', '၅': '5', '၆': '6', '၇': '7', '၈': '8', '၉': '9', '༠': '0', '༡': '1', '༢': '2', '༣': '3', '༤': '4', '༥': '5', '༦': '6', '༧': '7', '༨': '8', '༩': '9', '᠐': '0', '᠑': '1', '᠒': '2', '᠓': '3', '᠔': '4', '᠕': '5', '᠖': '6', '᠗': '7', '᠘': '8', '᠙': '9', '០': '0', '១': '1', '២': '2', '៣': '3', '៤': '4', '៥': '5', '៦': '6', '៧': '7', '៨': '8', '៩': '9', '๐': '0', '๑': '1', '๒': '2', '๓': '3', '๔': '4', '๕': '5', '๖': '6', '๗': '7', '๘': '8', '๙': '9', '໐': '0', '໑': '1', '໒': '2', '໓': '3', '໔': '4', '໕': '5', '໖': '6', '໗': '7', '໘': '8', '໙': '9', '꧐': '0', '꧑': '1', '꧒': '2', '꧓': '3', '꧔': '4', '꧕': '5', '꧖': '6', '꧗': '7', '꧘': '8', '꧙': '9', '٠': '0', '١': '1', '٢': '2', '٣': '3', '٤': '4', '٥': '5', '٦': '6', '٧': '7', '٨': '8', '٩': '9', '۰': '0', '۱': '1', '۲': '2', '۳': '3', '۴': '4', '۵': '5', '۶': '6', '۷': '7', '۸': '8', '۹': '9', '〇': '0', '一': '1', '二': '2', '三': '3', '四': '4', '五': '5', '六': '6', '七': '7', '八': '8', '九': '9', '零': '0'}
latin_numerals = ''.join([numerals_dict.get(letter, letter) for letter in s])
return int_saver(latin_numerals)
return(int_saver(s))
""")
def load_adventure_for_language(lang):
ADVENTURES[lang].set_keyword_language(g.keyword_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
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 = []
adventure_object = load_adventure_for_language(lang)
keywords = adventure_object.keywords
adventures = adventure_object.adventures_file['adventures']
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.get('default_save_name', adventure['name']),
'text': adventure['levels'][level].get('story_text', 'No Story Text').format(**keywords),
'example_code': adventure['levels'][level].get('example_code').format(**keywords) if adventure['levels'][level].get('example_code') else '',
'start_code': adventure['levels'][level].get('start_code').format(**keywords) if adventure['levels'][level].get('start_code') else '',
'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)).format(**keywords)
if adventure['levels'][level].get('example_code_' + str(i)):
extra_story['example_code'] = adventure['levels'][level].get('example_code_' + str(i)).format(**keywords)
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
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
babel = Babel(app)
# Return the session language, if not: return best match
@babel.localeselector
def get_locale():
return session.get("lang", request.accept_languages.best_match(ALL_LANGUAGES.keys(), 'en'))
"""
Some important notes relates to Flask-Babel usage:
- We can always get a translation using gettext('english string')
NOTE: We can shorten this notation by simply using _('english string')
- We can insert some variable like this: gettext('some string %(value)s', value=42)
- More interesting for us might be the 'lazy string' the can be defined outside requests, like this:
- lazy_gettext('Account successfully saved')
- This will be really useful when wanting to return translated error messages
- We have to mark ALL translatable string (in english!) with gettext() -> then create a .pot file
- We create the file as follows:
pybabel extract -F babel.cfg -o messages.pot .
- To add a translation (for dutch):
pybabel init -i messages.pot -d translations -l nl
- To update your files (when adding new strings):
FIRST create new file: pybabel extract -F babel.cfg -o messages.pot .
THEN: pybabel update -i messages.pot -d translations
LASTLY compile the files: pybabel compile -d translations
"""
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
utils.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')
if 'keyword_lang' not in session:
session['keyword_lang'] = "en"
g.lang = session['lang']
g.keyword_lang = session['keyword_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
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():
session['set_keyword_lang'] = False
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 user_data.get('language', '') in ALL_LANGUAGES.keys():
g.lang = session['lang'] = user_data['language']
if user_data.get('keyword_language', '') in ALL_LANGUAGES.keys():
g.keyword_lang = session['keyword_lang'] = user_data['keyword_language']
session['set_keyword_lang'] = True
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.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=utils.session_id(), username=username)
try:
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, 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)
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': utils.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
error_check = False
if 'error_check' in body:
error_check = True
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=utils.session_id(), username=username)
try:
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, 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, 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, ex.arguments)
response['Location'] = ex.error_location
transpile_result = ex.fixed_result
exception = ex
except hedy.exceptions.UnquotedEqualityCheck as ex:
response['Error'] = translate_error(ex.error_code, ex.arguments)
response['Location'] = ex.error_location
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)
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': utils.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)
})
if "Error" in response and error_check:
response["message"] = gettext('program_contains_error')
return jsonify(response)
@app.route('/parse-by-id', methods=['POST'])
@requires_login
def parse_by_id(user):
body = request.json
#Validations
if not isinstance(body, dict):
return 'body must be an object', 400
if not isinstance(body.get('id'), str):
return 'class id must be a string', 400
program = DATABASE.program_by_id(body.get('id'))
if program and program.get('username') == user['username']:
try:
hedy.transpile(program.get('code'), program.get('level'), program.get('lang'))
return {}, 200
except:
return {"error": "parsing error"}, 200
else:
return 'this is not your program!', 400
def transpile_add_stats(code, level, lang_):
username = current_user()['username'] or None
try:
result = hedy.transpile(code, level, lang_)
statistics.add(username, lambda id_: DATABASE.add_program_stats(id_, level, None))
return result
except Exception as ex:
statistics.add(username, lambda id_: DATABASE.add_program_stats(id_, level, get_class_name(ex)))
raise
def get_class_name(i):
if i is not None:
return str(i.__class__.__name__)
return i
def hedy_error_to_response(ex):
return {
"Error": translate_error(ex.error_code, ex.arguments),
"Location": ex.error_location
}
def translate_error(code, 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']
# Todo TB -> We have to find a more delicate way to fix this: returns some gettext() errors
error_template = gettext('' + str(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(v)
else:
arguments[k] = gettext('' + str(v))
return error_template.format(**arguments)
def translate_list(args):
translated_args = [gettext('' + str(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" {gettext('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': utils.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=utils.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
# Todo: TB -> I wrote this once, but wouldn't it make more sense to simply throw a 302 error?
url = request.url.replace('/my-achievements', '/login')
return redirect(url, code=302)
achievement_translations = hedyweb.PageTranslations('achievements').get_page_translations(g.lang)
achievements = ACHIEVEMENTS_TRANSLATIONS.get_translations(g.lang)
return render_template('achievements.html', page_title=gettext('title_achievements'),
achievements=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=gettext('not_teacher'))
students = DATABASE.get_teacher_students(username)
if from_user not in students:
return utils.error_page(error=403, ui_message=gettext('not_enrolled'))
adventures = load_adventure_for_language(g.lang).adventures_file['adventures']
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=gettext('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 utils.error_page(error=403, ui_message=gettext('unauthorized'))
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 utils.error_page(error=403, ui_message=gettext('unauthorized'))
class_ = DATABASE.get_class(class_id)
if not class_ or class_['teacher'] != user['username'] or username_filter not in class_.get('students', []):
return utils.error_page(error=403, ui_message=gettext('unauthorized'))
(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 utils.error_page(error=403, ui_message=gettext('unauthorized'))
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):
program_age = now - date
if program_age < 1000 * 60 * 60:
measure = gettext('minutes')
date = round(program_age / (1000 * 60))
elif program_age < 1000 * 60 * 60 * 24:
measure = gettext('hours')
date = round(program_age / (1000 * 60 * 60))
else:
measure = gettext('days')
date = round(program_age / (1000 * 60 * 60 * 24))
age = {'time': str(date) + " " + measure}
return gettext('ago').format(**age)
# routing to index.html
@app.route('/ontrack', methods=['GET'], defaults={'level': '1', 'program_id': None})
@app.route('/onlinemasters', methods=['GET'], defaults={'level': '1', 'program_id': None})
@app.route('/onlinemasters/<int:level>', methods=['GET'], defaults={'program_id': None})
@app.route('/space_eu', methods=['GET'], defaults={'level': '1', 'program_id': None})
@app.route('/hedy', methods=['GET'], defaults={'level': '1', 'program_id': None})
@app.route('/hedy/<level>', methods=['GET'], defaults={'program_id': None})
@app.route('/hedy/<level>/<program_id>', methods=['GET'])
def index(level, program_id):
if re.match('\\d', level):
try:
g.level = level = int(level)
except:
return utils.error_page(error=404, ui_message=gettext('no_such_level'))
else:
return utils.error_page(error=404, ui_message=gettext('no_such_level'))
loaded_program = ''
adventure_name = ''
if program_id:
result = DATABASE.program_by_id(program_id)
if not result:
return utils.error_page(error=404, ui_message=gettext('no_such_program'))
user = current_user()
public_program = result.get('public')
# Verify that the program is either public, the current user is the creator, teacher or the user is admin
if not public_program and user['username'] != result['username'] and not is_admin(user):
if (not is_teacher(user)) or (is_teacher(user) and result['username'] not in DATABASE.get_teacher_students(user['username'])):
return utils.error_page(error=404, ui_message=gettext(u'no_such_program'))
loaded_program = {'code': result['code'], 'name': result['name'],
'adventure_name': result.get('adventure_name')}
if 'adventure_name' in result:
adventure_name = result['adventure_name']
adventures = load_adventures_per_level(g.lang, level)
customizations = {}
if current_user()['username']:
customizations = DATABASE.get_student_class_customizations(current_user()['username'])
level_defaults_for_lang = LEVEL_DEFAULTS[g.lang]
level_defaults_for_lang.set_keyword_language(g.keyword_lang)
if 'levels' in customizations:
available_levels = customizations['levels']
now = timems()
for current_level, timestamp in customizations.get('opening_dates', {}).items():
if utils.datetotimeordate(timestamp) > utils.datetotimeordate(utils.mstoisostring(now)):
try:
available_levels.remove(int(current_level))
except:
print("Error: there is an openings date without a level")
if level not in level_defaults_for_lang.levels and level <= hedy.HEDY_MAX_LEVEL:
return utils.error_page(error=404, ui_message=gettext('level_not_translated'))
if 'levels' in customizations and level not in available_levels:
return utils.error_page(error=403, ui_message=gettext('level_not_class'))
defaults = level_defaults_for_lang.get_defaults_for_level(level)
max_level = level_defaults_for_lang.max_level()
teacher_adventures = []
for adventure in customizations.get('teacher_adventures', []):
teacher_adventures.append(DATABASE.get_adventure(adventure))
enforce_developers_mode = False
if 'other_settings' in customizations and 'developers_mode' in customizations['other_settings']:
enforce_developers_mode = True
hide_cheatsheet = False
if 'other_settings' in customizations and 'hide_cheatsheet' in customizations['other_settings']:
hide_cheatsheet = True
return hedyweb.render_code_editor_with_tabs(
level_defaults=defaults,
max_level=max_level,
level_number=level,
version=version(),
adventures=adventures,
customizations=customizations,
hide_cheatsheet=hide_cheatsheet,
enforce_developers_mode=enforce_developers_mode,
teacher_adventures=teacher_adventures,
loaded_program=loaded_program,
adventure_name=adventure_name)
@app.route('/hedy/<id>/view', methods=['GET'])
def view_program(id):
user = current_user()
result = DATABASE.program_by_id(id)
if not result:
return utils.error_page(error=404, ui_message=gettext('no_such_program'))
public_program = result.get('public')
# Verify that the program is either public, the current user is the creator, teacher or the user is admin
if not public_program and user['username'] != result['username'] and not is_admin(user):
if (not is_teacher(user)) or (is_teacher(user) and result['username'] not in DATABASE.get_teacher_students(user['username'])):
return utils.error_page(error=404, ui_message=gettext(u'no_such_program'))
# If we asked for a specific language, use that, otherwise use the language
# of the program's author.
# Default to the language of the program's author(but still respect)
# the switch if given.
g.lang = request.args.get('lang', result['lang'])
arguments_dict = {}
arguments_dict['program_id'] = id
arguments_dict['page_title'] = f'{result["name"]} – Hedy'
arguments_dict['level'] = result['level'] # Necessary for running
arguments_dict['loaded_program'] = result
arguments_dict['editor_readonly'] = True
if "submitted" in result and result['submitted']:
arguments_dict['show_edit_button'] = False
now = timems()
arguments_dict['program_age'] = get_user_formatted_age(now, result['date'])
arguments_dict[
'program_timestamp'] = f"{datetime.datetime.fromtimestamp(result['date'] / 1000.0).strftime('%d-%m-%Y, %H:%M:%S')} GMT"
else:
arguments_dict['show_edit_button'] = True
# Everything below this line has nothing to do with this page and it's silly
# that every page needs to put in so much effort to re-set it
arguments_dict['menu'] = True
arguments_dict['username'] = user.get('username', None)
arguments_dict['is_teacher'] = is_teacher(user)
return render_template("view-program-page.html", **arguments_dict)
@app.route('/adventure/<name>', methods=['GET'], defaults={'level': 1})
@app.route('/adventure/<name>/<level>', methods=['GET'])
def get_specific_adventure(name, level):
try:
level = int(level)
except:
return utils.error_page(error=404, ui_message=gettext('no_such_level'))
adventure = [x for x in load_adventures_per_level(g.lang, level) if x.get('short_name') == name]
prev_level = level-1 if [x for x in load_adventures_per_level(g.lang, level-1) if x.get('short_name') == name] else False
next_level = level+1 if [x for x in load_adventures_per_level(g.lang, level+1) if x.get('short_name') == name] else False
print(prev_level)
print(next_level)
if not adventure:
return utils.error_page(error=404, ui_message=gettext('no_such_adventure'))
level_defaults_for_lang = LEVEL_DEFAULTS[g.lang]
defaults = level_defaults_for_lang.get_defaults_for_level(level)
return hedyweb.render_specific_adventure(
level_defaults=defaults, level_number=level, adventure=adventure, prev_level=prev_level, next_level=next_level)
@app.route('/cheatsheet/', methods=['GET'], defaults={'level': 1})
@app.route('/cheatsheet/<level>', methods=['GET'])
def get_cheatsheet_page(level):
level_defaults_for_lang = LEVEL_DEFAULTS[g.lang]
level_defaults_for_lang.set_keyword_language(g.keyword_lang)
defaults = level_defaults_for_lang.get_defaults_for_level(int(level))