forked from hedyorg/hedy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
2237 lines (1806 loc) · 82.4 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 collections
import copy
import logging
import json
import datetime
import os
import re
import sys
import traceback
import textwrap
import zipfile
from typing import Optional
from logging.config import dictConfig as logConfig
from os import path
import static_babel_content
from markupsafe import Markup
from flask import (Flask, Response, abort, after_this_request, g,
redirect, request, send_file, url_for, jsonify,
send_from_directory, session)
from flask_babel import Babel, gettext
from flask_commonmark import Commonmark
from flask_compress import Compress
from werkzeug.urls import url_encode
import hedy
import hedy_content
import hedy_translation
import hedyweb
import jinja_partials
import utils
from safe_format import safe_format
from config import config
from website.flask_helpers import render_template, proper_tojson, JinjaCompatibleJsonProvider
from hedy_content import (ADVENTURE_ORDER_PER_LEVEL, KEYWORDS_ADVENTURES, ALL_KEYWORD_LANGUAGES,
ALL_LANGUAGES, COUNTRIES)
from logging_config import LOGGING_CONFIG
from utils import dump_yaml_rt, is_debug_mode, load_yaml_rt, timems, version, strip_accents
from website import (ab_proxying, achievements, admin, auth_pages, aws_helpers,
cdn, classes, database, for_teachers, s3_logger, parsons,
profile, programs, querylog, quiz, statistics,
translating)
from website.auth import (current_user, is_admin, is_teacher,
login_user_from_token_cookie, requires_login, requires_login_redirect, requires_teacher)
from website.log_fetcher import log_fetcher
from website.frontend_types import Adventure, Program, ExtraStory, SaveInfo
logConfig(LOGGING_CONFIG)
logger = logging.getLogger(__name__)
# Todo TB: This can introduce a possible app breaking bug when switching
# to Python 4 -> e.g. Python 4.0.1 is invalid
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()
# Set the current directory to the root Hedy folder
os.chdir(os.path.join(os.getcwd(), __file__.replace(
os.path.basename(__file__), '')))
# Setting up Flask and babel (web and translations)
app = Flask(__name__, static_url_path='')
app.url_map.strict_slashes = False # Ignore trailing slashes in URLs
app.json = JinjaCompatibleJsonProvider(app)
babel = Babel(app)
jinja_partials.register_extensions(app)
app.template_filter('tojson')(proper_tojson)
COMMANDS = collections.defaultdict(hedy_content.NoSuchCommand)
for lang in ALL_LANGUAGES.keys():
COMMANDS[lang] = hedy_content.Commands(lang)
ADVENTURES = collections.defaultdict(hedy_content.NoSuchAdventure)
for lang in ALL_LANGUAGES.keys():
ADVENTURES[lang] = hedy_content.Adventures(lang)
PARSONS = collections.defaultdict()
for lang in ALL_LANGUAGES.keys():
PARSONS[lang] = hedy_content.ParsonsProblem(lang)
QUIZZES = collections.defaultdict(hedy_content.NoSuchQuiz)
for lang in ALL_LANGUAGES.keys():
QUIZZES[lang] = hedy_content.Quizzes(lang)
TUTORIALS = collections.defaultdict(hedy_content.NoSuchTutorial)
for lang in ALL_LANGUAGES.keys():
TUTORIALS[lang] = hedy_content.Tutorials(lang)
SLIDES = collections.defaultdict(hedy_content.NoSuchSlides)
for lang in ALL_LANGUAGES.keys():
SLIDES[lang] = hedy_content.Slides(lang)
ACHIEVEMENTS_TRANSLATIONS = hedyweb.AchievementTranslations()
DATABASE = database.Database()
ACHIEVEMENTS = achievements.Achievements(DATABASE, ACHIEVEMENTS_TRANSLATIONS)
def load_adventures_for_level(level):
"""Load the adventures available to the current user at the given level.
These are the default adventures, with the customizations implied
by any class they are a part of. We also load any programs the user has
that apply to the current level.
Adventures are loaded in the current language, with the keywords in the code
translated to the default (or explicitly requested) keyword language.
"""
keyword_lang = g.keyword_lang
all_adventures = []
adventures = ADVENTURES[g.lang].get_adventures(keyword_lang)
for short_name, adventure in adventures.items():
adventure_level = adventure['levels'].get(level, None)
if not adventure_level:
continue
# Sometimes we have multiple text and example_code -> iterate these and add as well!
extra_stories = [
ExtraStory(
text=adventure_level.get(f'story_text_{i}'),
example_code=adventure_level.get(f'example_code_{i}'))
for i in range(2, 10)
if adventure_level.get(f'story_text_{i}', '')
]
default_save_name = adventure.get('default_save_name')
if not default_save_name or default_save_name == 'intro':
default_save_name = adventure['name']
# only add adventures that have been added to the adventure list of this level
if short_name in ADVENTURE_ORDER_PER_LEVEL.get(level, []):
current_adventure = Adventure(
short_name=short_name,
name=adventure['name'],
image=adventure.get('image', None),
text=adventure['levels'][level].get('story_text', ""),
example_code=adventure['levels'][level].get('example_code', ""),
extra_stories=extra_stories,
is_teacher_adventure=False,
is_command_adventure=short_name in KEYWORDS_ADVENTURES,
save_name=f'{default_save_name} {level}',
start_code=adventure['levels'][level].get('start_code', ""))
all_adventures.append(current_adventure)
# Sort the adventures based on the default ordering
adventures_order = ADVENTURE_ORDER_PER_LEVEL.get(level, [])
index_map = {v: i for i, v in enumerate(adventures_order)}
all_adventures.sort(key=lambda pair: index_map.get(
pair['short_name'],
len(adventures_order)))
return all_adventures
def load_saved_programs(level, into_adventures, preferential_program: Optional[Program]):
"""Load saved previous saved programs by the current user into the given adventures array.
Mutates the adventures in-place, by setting the 'save_name', 'start_code'
and 'save_info' attributes of adventures.
"""
if not current_user()['username']:
return
loaded_programs = {k: Program.from_database_row(r)
for k, r in DATABASE.last_level_programs_for_user(current_user()['username'], level).items()}
# If there is a preferential program, overwrite any other one that might exist so we definitely
# load this one.
if preferential_program:
loaded_programs[preferential_program.adventure_name] = preferential_program
# Copy them into the adventures array
#
# For every adventure, find a program in the `loaded_programs` dictionary.
# Since the program may be saved under either the id or the actual name, check both.
for adventure in into_adventures:
program = loaded_programs.get(adventure.short_name)
if not program:
program = loaded_programs.get(adventure.name)
if not program:
continue
adventure.save_name = program.name
adventure.start_code = program.code
adventure.save_info = SaveInfo.from_program(program)
def load_customized_adventures(level, customizations, into_adventures):
"""Load the teacher customizations into the set of adventures.
It would have been nicer if the complete set of adventures had come
out of 'load_adventures_for_level', but looking up customizations is
a bit expensive and since we've already done that in the caller, we pass
it in here.
Mutates the 'into_adventures' list in-place. On entry, it is the list of
default `Adventure` objects in the default order. On exit, it may have been
reordered and enhanced with teacher-written adventures.
"""
# First find the list of all teacher adventures for the current level,
# batch-get all of them, then put them into the adventures array in the correct
# location.
# { <str>level -> [ { <str>name, <bool>from_teacher ] }
# 'name' is either a shortname or an ID into the teacher table
sorted_adventures = customizations.get('sorted_adventures', {})
order_for_this_level = sorted_adventures.get(str(level), [])
if not order_for_this_level:
return # Nothing to do
adventure_ids = {a['name'] for a in order_for_this_level if a['from_teacher']}
teacher_adventure_map = DATABASE.batch_get_adventures(adventure_ids)
builtin_adventure_map = {a.short_name: a for a in into_adventures}
# Replace `into_adventures`
into_adventures[:] = []
for a in order_for_this_level:
if a['from_teacher'] and (db_row := teacher_adventure_map.get(a['name'])):
try:
db_row['content'] = safe_format(db_row['content'],
**hedy_content.KEYWORDS.get(g.keyword_lang))
except Exception:
# We don't want teacher being able to break the student UI -> pass this adventure
pass
into_adventures.append(Adventure.from_teacher_adventure_database_row(db_row))
if not a['from_teacher'] and (adv := builtin_adventure_map.get(a['name'])):
into_adventures.append(adv)
@babel.localeselector
def get_locale():
return session.get("lang", request.accept_languages.best_match(ALL_LANGUAGES.keys(), 'en'))
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) + '?' + request.query_string.decode('utf-8')
) if request.query_string else str(request.path)
querylog.begin_global_log_record(
path=path,
method=request.method,
remote_ip=request.headers.get('X-Forwarded-For', request.remote_addr),
user_agent=request.headers.get('User-Agent'))
@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).
"""
# Set the database object on the global object (auth.py needs it)
g.db = DATABASE
# Invoke session_id() for its side effect
utils.session_id()
login_user_from_token_cookie()
g.user = current_user()
querylog.log_value(session_id=utils.session_id(), username=g.user['username'],
is_teacher=is_teacher(g.user), is_admin=is_admin(g.user))
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) and 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 = s3_logger.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. Can be changed in the session by
# POSTing to `/change_language`, and be overwritten by remember_current_user().
if lang_from_request := request.args.get('language', None):
session['lang'] = lang_from_request
if 'lang' not in session:
session['lang'] = request.accept_languages.best_match(
ALL_LANGUAGES.keys(), 'en')
g.lang = session['lang']
if 'keyword_lang' not in session:
session['keyword_lang'] = g.lang if g.lang in ALL_KEYWORD_LANGUAGES.keys() else 'en'
# If there is a '?keyword_language=' parameter, it overrides the current keyword lang, permanently
if request.args.get('keyword_language', None):
session['keyword_lang'] = request.args.get('keyword_language', None)
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 is rtl according to Locale (from Babel) settings.
# This is the only place to expand / shrink the list of RTL languages ->
# front-end is fixed based on this value
g.dir = static_babel_content.TEXT_DIRECTIONS.get(g.lang, 'ltr')
# 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'):
logger.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)}
return data
@app.context_processor
def add_generated_css_file():
return {
"generated_css_file": '/css/generated.full.css' if is_debug_mode() else '/css/generated.css'
}
@app.context_processor
def add_hx_detection():
"""Detect when a request is sent by HTMX.
A template may decide to render things differently when it is vs. when it isn't.
"""
hx_request = bool(request.headers.get('Hx-Request'))
return {
"hx_request": hx_request,
"hx_layout": 'htmx-layout-yes.html' if hx_request else 'htmx-layout-no.html',
}
@app.after_request
def hx_triggers(response):
"""For HTMX Requests, push any pending achievements in the session to the client.
Use the HX-Trigger header, which will trigger events on the client. There is a listener
there which will respond to the 'displayAchievements' event.
"""
if not request.headers.get('HX-Request'):
return response
achs = session.pop('pending_achievements', [])
if achs:
response.headers.set('HX-Trigger', json.dumps({'displayAchievements': achs}))
return response
@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):
log_record = querylog.finish_global_log_record(exc)
if is_debug_mode():
logger.debug(repr(log_record.as_data()))
# 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('/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:
keyword_lang = current_keyword_language()["lang"]
with querylog.log_time('transpile'):
try:
transpile_result = transpile_add_stats(code, level, lang)
if username and not body.get('tutorial'):
DATABASE.increase_user_run_count(username)
ACHIEVEMENTS.increase_count("run")
except hedy.exceptions.WarningException as ex:
translated_error = translate_error(ex.error_code, ex.arguments, keyword_lang)
if isinstance(ex, hedy.exceptions.InvalidSpaceException):
response['Warning'] = translated_error
else:
response['Error'] = translated_error
response['Location'] = ex.error_location
response['FixedCode'] = ex.fixed_code
transpile_result = ex.fixed_result
exception = ex
except hedy.exceptions.UnquotedEqualityCheck as ex:
response['Error'] = translate_error(ex.error_code, ex.arguments, keyword_lang)
response['Location'] = ex.error_location
exception = ex
try:
response['Code'] = transpile_result.code
response['source_map'] = transpile_result.source_map
if transpile_result.has_pygame:
response['has_pygame'] = True
if transpile_result.has_turtle:
response['has_turtle'] = True
except Exception:
pass
try:
response['has_sleep'] = 'sleep' in hedy.all_commands(code, level, lang)
except BaseException:
pass
try:
if username and not body.get('tutorial') 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
# Save this program (if the user is logged in)
if username and body.get('save_name'):
try:
program_logic = programs.ProgramsLogic(DATABASE, ACHIEVEMENTS)
program = program_logic.store_user_program(
user=current_user(),
level=level,
name=body.get('save_name'),
program_id=body.get('program_id'),
adventure_name=body.get('adventure_name'),
code=code,
error=exception is not None)
response['save_info'] = SaveInfo.from_program(Program.from_database_row(program))
except programs.NotYourProgramError:
# No permissions to overwrite, no biggie
pass
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 BaseException:
return {"error": "parsing error"}, 200
else:
return 'this is not your program!', 400
@app.route('/parse_tutorial', methods=['POST'])
@requires_login
def parse_tutorial(user):
body = request.json
code = body['code']
level = try_parse_int(body['level'])
try:
result = hedy.transpile(code, level, "en")
jsonify({'code': result.code}), 200
except BaseException:
return "error", 400
@app.route("/generate_machine_files", methods=['POST'])
def prepare_files():
body = request.json
# Prepare the file -> return the "secret" filename as response
transpiled_code = hedy.transpile(body.get("code"), body.get("level"), body.get("lang"))
filename = utils.random_id_generator(12)
# We have to turn the turtle 90 degrees to align with the user perspective app.ts#16
# This is not a really nice solution, but as we store the prefix on the
# front-end it should be good for now
threader = textwrap.dedent("""
import time
from turtlethread import Turtle
t = Turtle()
t.left(90)
with t.running_stitch(stitch_length=20):
""")
lines = transpiled_code.code.split("\n")
# remove all sleeps for speeed, and remove all colors for compatibility:
lines = [x for x in lines if ("time.sleep" not in x) and ("t.pencolor" not in x)]
threader += " " + "\n ".join(lines)
threader += "\n" + 't.save("machine_files/' + filename + '.dst")'
threader += "\n" + 't.save("machine_files/' + filename + '.png")'
if not os.path.isdir('machine_files'):
os.makedirs('machine_files')
exec(threader)
# stolen from: https://stackoverflow.com/questions/28568687/send-with-multiple-csvs-using-flask
zip_file = zipfile.ZipFile(f'machine_files/{filename}.zip', 'w', zipfile.ZIP_DEFLATED)
for root, dirs, files in os.walk('machine_files/'):
# only zip files for this request, and exclude the zip file itself:
for file in [x for x in files if x[:len(filename)] == filename and x[-3:] != 'zip']:
zip_file.write('machine_files/' + file)
zip_file.close()
return jsonify({'filename': filename}), 200
@app.route("/download_machine_files/<filename>", methods=['GET'])
def download_machine_file(filename, extension="zip"):
# https://stackoverflow.com/questions/24612366/delete-an-uploaded-file-after-downloading-it-from-flask
# Once the file is downloaded -> remove it
@after_this_request
def remove_file(response):
try:
os.remove("machine_files/" + filename + ".zip")
os.remove("machine_files/" + filename + ".dst")
os.remove("machine_files/" + filename + ".png")
except BaseException:
print("Error removing one of the generated files!")
return response
return send_file("machine_files/" + filename + "." + extension, as_attachment=True)
def transpile_add_stats(code, level, lang_):
username = current_user()['username'] or None
number_of_lines = code.count('\n')
try:
result = hedy.transpile(code, level, lang_)
statistics.add(
username, lambda id_: DATABASE.add_program_stats(id_, level, number_of_lines, None))
return result
except Exception as ex:
class_name = get_class_name(ex)
statistics.add(username, lambda id_: DATABASE.add_program_stats(
id_, level, number_of_lines, class_name))
raise
def get_class_name(i):
if i is not None:
return str(i.__class__.__name__)
return i
def hedy_error_to_response(ex):
keyword_lang = current_keyword_language()["lang"]
return {
"Error": translate_error(ex.error_code, ex.arguments, keyword_lang),
"Location": ex.error_location
}
def translate_error(code, arguments, keyword_lang):
arguments_that_require_translation = [
'allowed_types',
'invalid_type',
'invalid_type_2',
'character_found',
'concept',
'tip',
'else',
'command',
'print',
'ask',
'echo',
'is',
'if',
'repeat']
arguments_that_require_highlighting = [
'command',
'guessed_command',
'invalid_argument',
'invalid_argument_2',
'variable',
'invalid_value',
'print',
'else',
'ask',
'echo',
'is',
'if',
'repeat']
# Todo TB -> We have to find a more delicate way to fix this: returns some gettext() errors
error_template = gettext('' + str(code))
# Fetch tip if it exists and merge into template, since it can also contain placeholders
# that need to be translated/highlighted
if 'tip' in arguments:
error_template = error_template.replace("{tip}", gettext('' + str(arguments['tip'])))
# TODO, FH Oct 2022 -> Could we do this with a format even though we don't have all fields?
# adds keywords to the dictionary so they can be translated if they occur in the error text
# FH Oct 2022: this could be optimized by only adding them when they occur in the text
# (either with string matching or with a list of placeholders for each error)
arguments["print"] = "print"
arguments["ask"] = "ask"
arguments["echo"] = "echo"
arguments["else"] = "else"
arguments["repeat"] = "repeat"
arguments["is"] = "is"
arguments["if"] = "if"
# 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_translation:
if isinstance(v, list):
arguments[k] = translate_list(v)
else:
arguments[k] = gettext('' + str(v))
if k in arguments_that_require_highlighting:
if k in arguments_that_require_translation:
local_keyword = hedy_translation.translate_keyword_from_en(v, keyword_lang)
arguments[k] = hedy.style_command(local_keyword)
else:
arguments[k] = hedy.style_command(v)
return safe_format(error_template, **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)
@app.route('/commands/<id>')
def all_commands(id):
program = DATABASE.program_by_id(id)
code = program.get('code')
level = program.get('level')
lang = program.get('lang')
return render_template(
'commands.html',
commands=hedy.all_commands(code, level, lang))
@app.route('/my-achievements')
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)
user_achievements = DATABASE.achievements_by_username(user.get('username')) or []
achievements = ACHIEVEMENTS_TRANSLATIONS.get_translations(g.lang).get('achievements')
return render_template(
'achievements.html',
page_title=gettext('title_achievements'),
translations=achievements,
user_achievements=user_achievements,
current_page='my-profile')
@app.route('/programs', methods=['GET'])
@requires_login_redirect
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'))
# 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) or None
adventure = request.args.get('adventure', default=None, type=str) or None
page = request.args.get('page', default=None, type=str)
filter = request.args.get('filter', default=None, type=str)
submitted = True if filter == 'submitted' else None
result = DATABASE.filtered_programs_for_user(from_user or username,
level=level,
adventure=adventure,
submitted=submitted,
pagination_token=page,
limit=10)
programs = []
for item in result:
date = utils.delta_timestamp(item['date'])
# This way we only keep the first 4 lines to show as preview to the user
code = "\n".join(item['code'].split("\n")[:4])
programs.append(
{'id': item['id'],
'code': code,
'date': date,
'level': item['level'],
'name': item['name'],
'adventure_name': item.get('adventure_name'),
'submitted': item.get('submitted'),
'public': item.get('public'),
'number_lines': item['code'].count('\n') + 1
}
)
adventure_names = hedy_content.Adventures(g.lang).get_adventure_names()
next_page_url = url_for('programs_page', **dict(request.args, page=result.next_page_token)
) if result.next_page_token else None
return render_template(
'programs.html',
programs=programs,
page_title=gettext('title_programs'),
current_page='programs',
from_user=from_user,
public_profile=public_profile,
adventure_names=adventure_names,
max_level=hedy.HEDY_MAX_LEVEL,
next_page_url=next_page_url)
@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)