forked from hedyorg/hedy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
3141 lines (2577 loc) · 125 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 base64
import binascii
import collections
import logging
import datetime
import os
import re
# TEST
import subprocess
import sys
import traceback
import textwrap
import unicodedata
import zipfile
import jinja_partials
from typing import Optional
from logging.config import dictConfig as logConfig
from os import path
from iso639 import languages
import static_babel_content
from markupsafe import Markup
from flask import (Flask, Response, abort, after_this_request, g, jsonify, make_response,
redirect, request, send_file, url_for,
send_from_directory, session)
from flask_babel import Babel
from website.flask_helpers import gettext_with_fallback as gettext
from website.flask_commonmark import Commonmark
from flask_compress import Compress
from urllib.parse import quote_plus
import hedy
import hedy_content
import hedy_translation
import hedyweb
import utils
from hedy_error import get_error_text
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, HOUR_OF_CODE_ADVENTURES)
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, admin, auth_pages, aws_helpers,
cdn, classes, database, for_teachers, s3_logger, parsons,
profile, programs, querylog, quiz, statistics,
translating, tags, surveys, super_teacher, public_adventures, user_activity, feedback)
from website.auth import (current_user, is_admin, is_teacher, is_second_teacher, is_super_teacher, has_public_profile,
login_user_from_token_cookie, requires_login, requires_login_redirect, requires_teacher,
forget_current_user, hide_explore)
from website.log_fetcher import log_fetcher
from website.frontend_types import Adventure, Program, ExtraStory, SaveInfo
logConfig(LOGGING_CONFIG)
logger = logging.getLogger(__name__)
DATABASE = None
AUTH_MODULE = None
ACHIEVEMENTS_TRANSLATIONS = None
ACHIEVEMENTS = None
SURVEYS = None
STATISTICS = None
FOR_TEACHERS = None
# 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)
# Most files should be loaded through the CDN which has its own caching period and invalidation.
# Use 5 minutes as a reasonable default for all files we load elsewise.
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = datetime.timedelta(minutes=5)
def get_locale():
return session.get("lang", request.accept_languages.best_match(ALL_LANGUAGES.keys(), 'en'))
babel = Babel(app, locale_selector=get_locale)
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)
TAGS = collections.defaultdict(hedy_content.NoSuchAdventure)
for lang in ALL_LANGUAGES.keys():
TAGS[lang] = hedy_content.Tags(lang)
def load_all_adventures_for_index(customizations, subset=None):
"""
Loads all the default adventures in a dictionary that will be used to populate
the index, therfore we only need the titles and short names of the adventures.
"""
keyword_lang = g.keyword_lang
if subset:
adventures = ADVENTURES[g.lang].get_adventures_subset(subset, keyword_lang)
else:
adventures = ADVENTURES[g.lang].get_adventures(keyword_lang)
all_adventures = {i: [] for i in range(1, hedy.HEDY_MAX_LEVEL + 1)}
for short_name, adventure in adventures.items():
for level in adventure['levels']:
all_adventures[int(level)].append({
'short_name': short_name,
'name': adventure['name'],
'is_teacher_adventure': False,
'is_command_adventure': short_name in KEYWORDS_ADVENTURES
})
for level, adventures in all_adventures.items():
adventures_order = ADVENTURE_ORDER_PER_LEVEL.get(level, [])
index_map = {v: i for i, v in enumerate(adventures_order)}
adventures.sort(key=lambda pair: index_map.get(
pair['short_name'],
len(adventures_order)))
sorted_adventures = customizations.get('sorted_adventures')
if not sorted_adventures:
return all_adventures
builtin_map = {i: [] for i in range(1, hedy.HEDY_MAX_LEVEL + 1)}
adventure_ids = []
for level, order_for_level in sorted_adventures.items():
for a in order_for_level:
if a['from_teacher']:
adventure_ids.append(a['name'])
builtin_map[int(level)] = {a['short_name']: a for a in all_adventures[int(level)]}
teacher_adventure_map = DATABASE.batch_get_adventures(adventure_ids)
all_adventures = {i: [] for i in range(1, hedy.HEDY_MAX_LEVEL + 1)}
for level, order_for_level in sorted_adventures.items():
for adventure in order_for_level:
if adventure['from_teacher'] and (db_row := teacher_adventure_map.get(adventure['name'])):
all_adventures[int(level)].append({
'short_name': db_row['id'],
'name': db_row['name'],
'is_teacher_adventure': True,
'is_command_adventure': False
})
if not adventure['from_teacher'] and (adv := builtin_map[int(level)].get(adventure['name'])):
all_adventures[int(level)].append(adv)
return all_adventures
def load_adventures_for_level(level, subset=None):
"""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 = []
# NOTE: if we ever have ADVENTURES in the DB, adjust how the "levels" field is used.
if subset:
adventures = ADVENTURES[g.lang].get_adventures_subset(subset, keyword_lang)
else:
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}')
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'
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
student_adventure_id = f"{current_user()['username']}-{program['adventure_name']}-{level}"
student_adventure = DATABASE.student_adventure_by_id(student_adventure_id)
adventure.save_name = program.name
adventure.editor_contents = program.code
adventure.save_info = SaveInfo.from_program(program)
adventure.is_checked = (student_adventure and student_adventure['ticked']) is True
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:
if 'formatted_content' in db_row:
db_row['formatted_content'] = safe_format(db_row['formatted_content'],
**hedy_content.KEYWORDS.get(g.keyword_lang))
else:
db_row['content'] = safe_format(db_row['content'],
**hedy_content.KEYWORDS.get(g.keyword_lang))
if 'solution_example' in db_row:
db_row['solution_example'] = safe_format(db_row['solution_example'],
**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)
cdn.Cdn(app, os.getenv('CDN_PREFIX'), os.getenv('HEROKU_SLUG_COMMIT', 'dev'))
@app.before_request
def redirect_outdated_domains():
"""If Hedy is being loaded from a domain we no longer use or advertise,
do a 301 redirect to the official 'hedy.org' domain.
If we keep this up for long enough, eventually Google will update its index
to forget about the old domains.
"""
# request.host looks like 'hostname[:port]'
host = request.host.split(':')[0]
if host in ['hedycode.com', 'hedy-beta.herokuapp.com']:
# full_path starts with '/' and has everything
return redirect(f'https://hedy.org{request.full_path}', code=301)
@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), is_super_teacher=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)
# Explicitly substitute the flask gettext function with our custom definition which uses fallback languages
app.jinja_env.globals.update(_=gettext)
# We don't need to log in offline mode
if utils.is_offline_mode():
parse_logger = s3_logger.NullLogger()
else:
parse_logger = s3_logger.S3Logger(name="parse", config_key="s3-parse-logs")
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']
querylog.log_value(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')
# True if it is a Latin alphabet, False if not
g.latin = all('LATIN' in unicodedata.name(char, '').upper() for char in current_language()['sym'])
# Check that requested language is supported, otherwise return 404
if g.lang not in ALL_LANGUAGES.keys():
return make_response(gettext("request_invalid"), 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_second_teacher': is_second_teacher(user),
'is_admin': is_admin(user), 'has_public_profile': has_public_profile(user),
'is_super_teacher': is_super_teacher(user),
'hide_explore': hide_explore(g.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 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 make_response(gettext("request_invalid"), 400)
return make_response({'session': dict(session)})
@app.route('/session_main', methods=['GET'])
def echo_session_vars_main():
if not utils.is_testing_request(request):
return make_response(gettext("request_invalid"), 400)
return make_response({'session': dict(session),
'proxy_enabled': bool(os.getenv('PROXY_TO_TEST_HOST'))})
@app.route('/parse', methods=['POST'])
@querylog.timed_as('parse_handler')
def parse():
body = request.json
if not body:
return make_response(gettext("request_invalid"), 400)
if 'code' not in body:
return make_response(gettext("request_invalid"), 400)
if 'level' not in body:
return make_response(gettext("request_invalid"), 400)
if 'adventure_name' in body and not isinstance(body['adventure_name'], str):
return make_response(gettext("request_invalid"), 400)
if 'is_debug' not in body:
return make_response(gettext("request_invalid"), 400)
if 'raw' not in body:
return make_response(gettext("request_invalid"), 400)
error_check = False
if 'error_check' in body:
error_check = True
code = body['code']
level = int(body['level'])
is_debug = bool(body['is_debug'])
# 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, is_debug)
except hedy.exceptions.WarningException as ex:
translated_error = get_error_text(ex, keyword_lang)
if isinstance(ex, hedy.exceptions.InvalidSpaceException):
response['Warning'] = translated_error
elif isinstance(ex, hedy.exceptions.UnusedVariableException):
response['Warning'] = translated_error
else:
response['Error'] = translated_error
response['Location'] = ex.error_location
transpile_result = ex.fixed_result
exception = ex
except hedy.exceptions.UnquotedEqualityCheckException as ex:
response['Error'] = get_error_text(ex, keyword_lang)
response['Location'] = ex.error_location
exception = ex
try:
response['Code'] = transpile_result.code
source_map_result = transpile_result.source_map.get_result()
for i, mapping in source_map_result.items():
if mapping['error'] is not None:
source_map_result[i]['error'] = get_error_text(source_map_result[i]['error'], keyword_lang)
response['source_map'] = source_map_result
if transpile_result.has_pressed:
response['has_pressed'] = True
if transpile_result.has_turtle:
response['has_turtle'] = True
if transpile_result.has_clear:
response['has_clear'] = True
if transpile_result.has_music:
response['has_music'] = True
if transpile_result.has_sleep:
response['has_sleep'] = True
response['variables'] = transpile_result.roles_of_variables
except Exception:
pass
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, FOR_TEACHERS)
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'),
short_name=body.get('short_name'),
code=code,
error=exception is not None)
response['save_info'] = SaveInfo.from_program(Program.from_database_row(program))
if program.get('is_modified'):
response['is_modified'] = True
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 make_response(response, 200)
@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 make_response('', 204)
except BaseException:
make_response(gettext("request_invalid"), 200)
else:
return make_response(gettext("request_invalid"), 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")
# this is not a return, is this code needed?
make_response(({'code': result.code}), 200)
except BaseException:
return make_response(gettext("request_invalid"), 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
def int_with_error(value, error_message):
try:
return int(value)
except ValueError:
raise ValueError(error_message.format(value))
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 make_response({'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)
MICROBIT_FEATURE = False
@app.route('/generate_microbit_files', methods=['POST'])
def generate_microbit_file():
if MICROBIT_FEATURE:
# Extract variables from request body
body = request.json
code = body.get("code")
level = body.get("level")
transpile_result = hedy.transpile_and_return_python(code, level)
save_transpiled_code_for_microbit(transpile_result)
return make_response({'filename': 'Micro-bit.py', 'microbit': True}, 200)
else:
return make_response({'message': 'Microbit feature is disabled'}, 403)
def save_transpiled_code_for_microbit(transpiled_python_code):
folder = 'Micro-bit'
filepath = os.path.join(folder, 'Micro-bit.py')
if not os.path.exists(folder):
os.makedirs(folder)
with open(filepath, 'w') as file:
custom_string = "from microbit import *\nimport random"
file.write(custom_string + "\n")
# file.write(transpiled_python_code + "\n")
# Splitting strings to new lines, so it can be properly displayed by Micro:bit
processed_code = ""
lines = transpiled_python_code.split('\n')
for line in lines:
if "display.scroll" in line:
# Extract the content inside display.scroll()
match = re.search(r"display\.scroll\((.*)\)", line)
if match:
content = match.group(1)
# Split the content by quoted strings and variables
parts = re.findall(r"('[^']*')|([^',]+)", content)
for part in parts:
part = part[0] or part[1]
if part.strip():
processed_code += f"display.scroll({part.strip()})\n"
else:
processed_code += line + "\n"
# Write the processed code
file.write(processed_code)
@app.route('/download_microbit_files/', methods=['GET'])
def convert_to_hex_and_download():
if MICROBIT_FEATURE:
flash_micro_bit()
current_directory = os.path.dirname(os.path.abspath(__file__))
micro_bit_directory = os.path.join(current_directory, 'Micro-bit')
@after_this_request
def remove_file(response):
try:
os.remove("Micro-bit/micropython.hex")
os.remove("Micro-bit/Micro-bit.py")
except BaseException:
print("Error removing one of the generated files!")
return response
return send_file(os.path.join(micro_bit_directory, "micropython.hex"), as_attachment=True)
else:
return make_response({'message': 'Microbit feature is disabled'}, 403)
def flash_micro_bit():
subprocess.run(['uflash', "Micro-bit/Micro-bit.py", "Micro-bit"])
def transpile_add_stats(code, level, lang_, is_debug):
username = current_user()['username'] or None
number_of_lines = code.count('\n')
try:
result = hedy.transpile(code, level, lang_, is_debug=is_debug)
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": get_error_text(ex, keyword_lang),
"Location": ex.error_location
}
@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('/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