forked from oppia/oppia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
1506 lines (1162 loc) · 47.1 KB
/
utils.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
# Copyright 2014 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Common utility functions."""
from __future__ import annotations
import base64
import binascii
import collections
import datetime
import hashlib
import imghdr
import io
import itertools
import json
import os
import random
import re
import ssl
import string
import time
import unicodedata
import urllib.parse
import urllib.request
import zlib
from core import feconf
from core.constants import constants
from PIL import Image
import certifi
import yaml
from typing import ( # isort:skip
Any, BinaryIO, Callable, Dict, Iterable, Iterator, List, Mapping,
Literal, Optional, TextIO, Tuple, TypeVar, Union, cast, overload)
DATETIME_FORMAT = '%m/%d/%Y, %H:%M:%S:%f'
ISO_8601_DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S.%fz'
PNG_DATA_URL_PREFIX = 'data:image/png;base64,'
DATA_URL_FORMAT_PREFIX = 'data:image/%s;base64,'
SECONDS_IN_HOUR = 60 * 60
SECONDS_IN_MINUTE = 60
T = TypeVar('T')
TextModeTypes = Literal['r', 'w', 'a', 'x', 'r+', 'w+', 'a+']
BinaryModeTypes = Literal['rb', 'wb', 'ab', 'xb', 'r+b', 'w+b', 'a+b', 'x+b']
class InvalidInputException(Exception):
"""Error class for invalid input."""
pass
class ValidationError(Exception):
"""Error class for when a domain object fails validation."""
pass
class DeprecatedCommandError(ValidationError):
"""Error class for when a domain object has a command
or a value that is deprecated.
"""
pass
class ExplorationConversionError(Exception):
"""Error class for when an exploration fails to convert from a certain
version to a certain version.
"""
pass
@overload
def open_file(
filename: str,
mode: TextModeTypes,
encoding: str = 'utf-8',
newline: Union[str, None] = None
) -> TextIO: ...
@overload
def open_file(
filename: str,
mode: BinaryModeTypes,
encoding: Union[str, None] = 'utf-8',
newline: Union[str, None] = None
) -> BinaryIO: ...
def open_file(
filename: str,
mode: Union[TextModeTypes, BinaryModeTypes],
encoding: Union[str, None] = 'utf-8',
newline: Union[str, None] = None
) -> Union[BinaryIO, TextIO]:
"""Open file and return a corresponding file object.
Args:
filename: str. The file to be opened.
mode: Literal. Mode in which the file is opened.
encoding: str. Encoding in which the file is opened.
newline: None|str. Controls how universal newlines work.
Returns:
IO[Any]. The file object.
Raises:
FileNotFoundError. The file cannot be found.
"""
# Here we use cast because we are narrowing down the type from IO[Any]
# to Union[BinaryIO, TextIO].
file = cast(
Union[BinaryIO, TextIO],
open(filename, mode, encoding=encoding, newline=newline)
)
return file
@overload
def get_file_contents(filepath: str) -> str: ...
@overload
def get_file_contents(
filepath: str, *, mode: str = 'r'
) -> str: ...
@overload
def get_file_contents(
filepath: str, *, raw_bytes: Literal[False], mode: str = 'r'
) -> str: ...
@overload
def get_file_contents(
filepath: str, *, raw_bytes: Literal[True], mode: str = 'r'
) -> bytes: ...
def get_file_contents(
filepath: str, raw_bytes: bool = False, mode: str = 'r'
) -> Union[str, bytes]:
"""Gets the contents of a file, given a relative filepath
from oppia.
Args:
filepath: str. A full path to the file.
raw_bytes: bool. Flag for the raw_bytes output.
mode: str. File opening mode, default is in read mode.
Returns:
Union[str, bytes]. Either the raw_bytes stream ( bytes type ) if
the raw_bytes is True or the decoded stream ( string type ) in
utf-8 format if raw_bytes is False.
"""
if raw_bytes:
mode = 'rb'
encoding = None
else:
encoding = 'utf-8'
with open(
filepath, mode, encoding=encoding) as f:
file_contents = f.read()
# Ruling out the possibility of Any other type for mypy type checking.
assert isinstance(file_contents, (str, bytes))
return file_contents
def get_exploration_components_from_dir(
dir_path: str
) -> Tuple[str, List[Tuple[str, bytes]]]:
"""Gets the (yaml, assets) from the contents of an exploration data dir.
Args:
dir_path: str. A full path to the exploration root directory.
Returns:
*. A 2-tuple, the first element of which is a yaml string, and the
second element of which is a list of (filepath, content) 2-tuples.
The filepath does not include the assets/ prefix.
Raises:
Exception. If the following condition doesn't hold: "There
is exactly one file not in assets/, and this file has a
.yaml suffix".
"""
yaml_content = None
assets_list = []
dir_path_array = dir_path.split('/')
while dir_path_array[-1] == '':
dir_path_array = dir_path_array[:-1]
dir_path_length = len(dir_path_array)
for root, directories, files in os.walk(dir_path):
for directory in directories:
if root == dir_path and directory not in ('assets', '__pycache__'):
raise Exception(
'The only directory in %s should be assets/' % dir_path)
for filename in files:
filepath = os.path.join(root, filename)
if root == dir_path:
# These files are added automatically by Mac OS Xsystems.
# We ignore them.
if not filepath.endswith('.DS_Store'):
if yaml_content is not None:
raise Exception(
'More than one non-asset file specified '
'for %s' % dir_path)
if not filepath.endswith('.yaml'):
raise Exception(
'Found invalid non-asset file %s. There '
'should only be a single non-asset file, '
'and it should have a .yaml suffix.' % filepath)
yaml_content = get_file_contents(filepath)
else:
filepath_array = filepath.split('/')
# The additional offset is to remove the 'assets/' prefix.
filename = '/'.join(filepath_array[dir_path_length + 1:])
assets_list.append((filename, get_file_contents(
filepath, raw_bytes=True)))
if yaml_content is None:
raise Exception('No yaml file specifed for %s' % dir_path)
return yaml_content, assets_list
def get_comma_sep_string_from_list(items: List[str]) -> str:
"""Turns a list of items into a comma-separated string.
Args:
items: list(str). List of the items.
Returns:
str. String containing the items in the list separated by commas.
"""
if not items:
return ''
if len(items) == 1:
return items[0]
return '%s and %s' % (', '.join(items[:-1]), items[-1])
def to_ascii(input_string: str) -> str:
"""Change unicode characters in a string to ascii if possible.
Args:
input_string: str. String to convert.
Returns:
str. String containing the ascii representation of the input string.
"""
normalized_string = unicodedata.normalize('NFKD', str(input_string))
return normalized_string.encode('ascii', 'ignore').decode('ascii')
# Here we use type Any because this function accepts general structured
# yaml string, hence Any type has to be used here for the type of returned
# dictionary.
def dict_from_yaml(yaml_str: str) -> Dict[str, Any]:
"""Gets the dict representation of a YAML string.
Args:
yaml_str: str. Yaml string for conversion into dict.
Returns:
dict. Parsed dict representation of the yaml string.
Raises:
InvalidInputException. If the yaml string sent as the
parameter is unable to get parsed, them this error gets
raised.
"""
try:
retrieved_dict = yaml.safe_load(yaml_str)
assert isinstance(retrieved_dict, dict)
return retrieved_dict
except (AssertionError, yaml.YAMLError) as e:
raise InvalidInputException(e) from e
# Here we use type Any because we want to accept both Dict and TypedDict
# types of values here.
def yaml_from_dict(dictionary: Mapping[str, Any], width: int = 80) -> str:
"""Gets the YAML representation of a dict.
Args:
dictionary: dict. Dictionary for conversion into yaml.
width: int. Width for the yaml representation, default value
is set to be of 80.
Returns:
str. Converted yaml of the passed dictionary.
"""
yaml_str: str = yaml.dump(
dictionary, allow_unicode=True, width=width
)
return yaml_str
# Here we use type Any because here obj has a recursive structure. The list
# element or dictionary value could recursively be the same structure, hence
# we use Any as their types.
def recursively_remove_key(
obj: Union[Dict[str, Any], List[Any]], key_to_remove: str
) -> None:
"""Recursively removes keys from a list or dict.
Args:
obj: *. List or dict passed for which the keys has to
be removed.
key_to_remove: str. Key value that has to be removed.
Returns:
*. Dict or list with a particular key value removed.
"""
if isinstance(obj, list):
for item in obj:
recursively_remove_key(item, key_to_remove)
elif isinstance(obj, dict):
if key_to_remove in obj:
del obj[key_to_remove]
for key, unused_value in obj.items():
recursively_remove_key(obj[key], key_to_remove)
def get_random_int(upper_bound: int) -> int:
"""Returns a random integer in [0, upper_bound).
Args:
upper_bound: int. Upper limit for generation of random
integer.
Returns:
int. Randomly generated integer less than the upper_bound.
"""
assert upper_bound >= 0 and isinstance(upper_bound, int), (
'Only positive integers allowed'
)
generator = random.SystemRandom()
return generator.randrange(0, stop=upper_bound)
def get_random_choice(alist: List[T]) -> T:
"""Gets a random element from a list.
Args:
alist: list(*). Input to get a random choice.
Returns:
*. Random element choosen from the passed input list.
"""
assert isinstance(alist, list) and len(alist) > 0, (
'Only non-empty lists allowed'
)
index = get_random_int(len(alist))
return alist[index]
def get_url_scheme(url: str) -> str:
"""Gets the url scheme used by a link.
Args:
url: str. The URL.
Returns:
str. Returns the URL scheme.
"""
return urllib.parse.urlparse(url).scheme
def convert_png_binary_to_webp_binary(png_binary: bytes) -> bytes:
"""Convert png binary to webp binary.
Args:
png_binary: bytes. The binary content of png.
Returns:
bytes. The binary content of webp.
"""
with io.BytesIO() as output:
image = Image.open(io.BytesIO(png_binary)).convert('RGB')
image.save(output, 'webp')
return output.getvalue()
def convert_data_url_to_binary(
image_data_url: str, file_type: str
) -> bytes:
"""Converts a PNG or WEBP base64 data URL to a PNG binary data.
Args:
image_data_url: str. A string that is to be interpreted as a PNG
or WEBP data URL.
file_type: str. Type of the data url, webp or png.
Returns:
bytes. Binary content of the PNG or WEBP created from the data URL.
Raises:
Exception. The given string does not represent a PNG data URL.
"""
if image_data_url.startswith(DATA_URL_FORMAT_PREFIX % file_type):
return base64.b64decode(
urllib.parse.unquote(
image_data_url[len(DATA_URL_FORMAT_PREFIX % file_type):]))
else:
raise Exception(
'The given string does not represent a %s data URL.' % file_type)
def convert_image_binary_to_data_url(
content: bytes, file_type: str
) -> str:
"""Converts a PNG or WEBP image string (represented by 'content')
to a data URL.
Args:
content: str. PNG or WEBP binary file content.
file_type: str. Type of the binary data, webp or png.
Returns:
str. Data URL created from the binary content of the PNG or WEBP.
Raises:
Exception. The given binary string does not represent a PNG image.
Exception. The given binary string does not represent a WEBP image.
"""
if imghdr.what(None, h=content) == file_type:
return '%s%s' % (
DATA_URL_FORMAT_PREFIX % file_type,
urllib.parse.quote(base64.b64encode(content))
)
else:
raise Exception(
'The given string does not represent a %s image.' % file_type)
def is_base64_encoded(content: str) -> bool:
"""Checks if a string is base64 encoded.
Args:
content: str. String to check.
Returns:
bool. True if a string is base64 encoded, False otherwise.
"""
try:
base64.b64decode(content, validate=True)
return True
except binascii.Error:
return False
def convert_png_to_data_url(filepath: str) -> str:
"""Converts the png file at filepath to a data URL.
Args:
filepath: str. A full path to the file.
Returns:
str. Data url created from the filepath of the PNG.
"""
file_contents = get_file_contents(filepath, raw_bytes=True, mode='rb')
return convert_image_binary_to_data_url(file_contents, 'png')
def camelcase_to_hyphenated(camelcase_str: str) -> str:
"""Camelcase to hyhpenated conversion of the passed string.
Args:
camelcase_str: str. Camelcase string representation.
Returns:
str. Hypenated string representation of the camelcase string.
"""
intermediate_str = re.sub('(.)([A-Z][a-z]+)', r'\1-\2', camelcase_str)
return re.sub('([a-z0-9])([A-Z])', r'\1-\2', intermediate_str).lower()
def camelcase_to_snakecase(camelcase_str: str) -> str:
"""Camelcase to snake case conversion of the passed string.
Args:
camelcase_str: str. Camelcase string representation.
Returns:
str. Snakecase representation of the passed camelcase string.
"""
intermediate_str = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', camelcase_str)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', intermediate_str).lower()
def set_url_query_parameter(
url: str, param_name: str, param_value: str
) -> str:
"""Set or replace a query parameter, and return the modified URL.
Args:
url: str. URL string which contains the query parameter.
param_name: str. Parameter name to be removed.
param_value: str. Set the parameter value, if it exists.
Returns:
str. Formated URL that has query parameter set or replaced.
Raises:
Exception. If the query parameter sent is not of string type,
them this exception is raised.
"""
if not isinstance(param_name, str):
raise Exception(
'URL query parameter name must be a string, received %s'
% param_name)
scheme, netloc, path, query_string, fragment = urllib.parse.urlsplit(url)
query_params = urllib.parse.parse_qs(query_string)
query_params[param_name] = [param_value]
new_query_string = urllib.parse.urlencode(query_params, doseq=True)
return urllib.parse.urlunsplit(
(scheme, netloc, path, new_query_string, fragment))
class JSONEncoderForHTML(json.JSONEncoder):
"""Encodes JSON that is safe to embed in HTML."""
# Ignoring error code [override] because JSONEncoder has return type str
# but we are returning Union[str, unicode].
def encode(self, o: str) -> str:
chunks = self.iterencode(o, True)
return ''.join(chunks) if self.ensure_ascii else u''.join(chunks)
def iterencode(self, o: str, _one_shot: bool = False) -> Iterator[str]:
chunks = super().iterencode(o, _one_shot=_one_shot)
for chunk in chunks:
yield chunk.replace('&', '\\u0026').replace(
'<', '\\u003c').replace('>', '\\u003e')
def convert_to_hash(input_string: str, max_length: int) -> str:
"""Convert a string to a SHA1 hash.
Args:
input_string: str. Input string for conversion to hash.
max_length: int. Maximum Length of the generated hash.
Returns:
str. Hash Value generated from the input_String of the
specified length.
Raises:
Exception. If the input string is not the instance of the str,
them this exception is raised.
"""
if not isinstance(input_string, str):
raise Exception(
'Expected string, received %s of type %s' %
(input_string, type(input_string)))
# Encodes strings using the character set [A-Za-z0-9].
# Prefixing altchars with b' to ensure that all characters in encoded_string
# remain encoded (otherwise encoded_string would be of type unicode).
encoded_string = base64.b64encode(
hashlib.sha1(input_string.encode('utf-8')).digest(),
altchars=b'ab'
).replace(b'=', b'c')
return encoded_string[:max_length].decode('utf-8')
def base64_from_int(value: int) -> str:
"""Converts the number into base64 representation.
Args:
value: int. Integer value for conversion into base64.
Returns:
str. Returns the base64 representation of the number passed.
"""
byte_value = b'[' + str(value).encode('utf-8') + b']'
return base64.b64encode(byte_value).decode('utf-8')
def get_time_in_millisecs(datetime_obj: datetime.datetime) -> float:
"""Returns time in milliseconds since the Epoch.
Args:
datetime_obj: datetime. An object of type datetime.datetime.
Returns:
float. The time in milliseconds since the Epoch.
"""
return datetime_obj.timestamp() * 1000.0
def convert_millisecs_time_to_datetime_object(
date_time_msecs: float) -> datetime.datetime:
"""Returns the datetime object from the given date time in milliseconds.
Args:
date_time_msecs: float. Date time represented in milliseconds.
Returns:
datetime. An object of type datetime.datetime corresponding to
the given milliseconds.
"""
return datetime.datetime.fromtimestamp(date_time_msecs / 1000.0)
def convert_naive_datetime_to_string(datetime_obj: datetime.datetime) -> str:
"""Returns a human-readable string representing the naive datetime object.
Args:
datetime_obj: datetime. An object of type datetime.datetime. Must be a
naive datetime object.
Returns:
str. The string representing the naive datetime object.
"""
return datetime_obj.strftime(DATETIME_FORMAT)
def convert_string_to_naive_datetime_object(
date_time_string: str
) -> datetime.datetime:
"""Returns the naive datetime object equivalent of the date string.
Args:
date_time_string: str. The string format representing the datetime
object in the format: Month/Day/Year,
Hour:Minute:Second:MicroSecond.
Returns:
datetime. An object of type naive datetime.datetime corresponding to
that string.
"""
return datetime.datetime.strptime(date_time_string, DATETIME_FORMAT)
def get_current_time_in_millisecs() -> float:
"""Returns time in milliseconds since the Epoch.
Returns:
float. The time in milliseconds since the Epoch.
"""
return get_time_in_millisecs(
datetime.datetime.now(datetime.timezone.utc)
)
def get_human_readable_time_string(time_msec: float) -> str:
"""Given a time in milliseconds since the epoch, get a human-readable
time string for the admin dashboard.
Args:
time_msec: float. Time in milliseconds since the Epoch.
Returns:
str. A string representing the time.
"""
# Ignoring arg-type because we are preventing direct usage of 'str' for
# Python3 compatibilty.
assert time_msec >= 0, (
'Time cannot be negative'
)
return time.strftime(
'%B %d %H:%M:%S', time.gmtime(time_msec / 1000.0))
def get_number_of_days_since_date(date: datetime.date) -> int:
"""Returns the number of days past since a given date.
Args:
date: datetime.date. Date since when the number of days is to
calculated.
Returns:
int. The number of days past since a given date.
"""
return int((datetime.date.today() - date).days)
def create_string_from_largest_unit_in_timedelta(
timedelta_obj: datetime.timedelta
) -> str:
"""Given the timedelta object, find the largest nonzero time unit and
return that value, along with the time unit, as a human readable string.
The returned string is not localized.
Args:
timedelta_obj: datetime.timedelta. A datetime timedelta object. Datetime
timedelta objects are created when you subtract two datetime
objects.
Returns:
str. A human readable string representing the value of the largest
nonzero time unit, along with the time units. If the largest time unit
is seconds, 1 minute is returned. The value is represented as an integer
in the string.
Raises:
Exception. If the provided timedelta is not positive.
"""
total_seconds = timedelta_obj.total_seconds()
if total_seconds <= 0:
raise Exception(
'Expected a positive timedelta, received: %s.' % total_seconds)
if timedelta_obj.days != 0:
return '%s day%s' % (
int(timedelta_obj.days), 's' if timedelta_obj.days > 1 else '')
else:
number_of_hours, remainder = divmod(total_seconds, SECONDS_IN_HOUR)
number_of_minutes, _ = divmod(remainder, SECONDS_IN_MINUTE)
if number_of_hours != 0:
return '%s hour%s' % (
int(number_of_hours), 's' if number_of_hours > 1 else '')
elif number_of_minutes > 1:
return '%s minutes' % int(number_of_minutes)
# Round any seconds up to one minute.
else:
return '1 minute'
def are_datetimes_close(
later_datetime: datetime.datetime,
earlier_datetime: datetime.datetime
) -> bool:
"""Given two datetimes, determines whether they are separated by less than
feconf.PROXIMAL_TIMEDELTA_SECS seconds.
Args:
later_datetime: datetime. The later datetime.
earlier_datetime: datetime. The earlier datetime.
Returns:
bool. True if difference between two datetimes is less than
feconf.PROXIMAL_TIMEDELTA_SECS seconds otherwise false.
"""
difference_in_secs = (later_datetime - earlier_datetime).total_seconds()
return difference_in_secs < feconf.PROXIMAL_TIMEDELTA_SECS
def generate_random_string(length: int) -> str:
"""Generates a random string of the specified length.
Args:
length: int. Length of the string to be generated.
Returns:
str. Random string of specified length.
"""
return base64.urlsafe_b64encode(os.urandom(length))[:length].decode('utf-8')
def generate_new_session_id() -> str:
"""Generates a new session id.
Returns:
str. Random string of length 24.
"""
return generate_random_string(24)
def vfs_construct_path(base_path: str, *path_components: str) -> str:
"""Mimics behavior of os.path.join on Posix machines.
Args:
base_path: str. The initial path upon which components would be added.
*path_components: list(str). Components that would be added to the path.
Returns:
str. The path that is obtained after adding the components.
"""
return os.path.join(base_path, *path_components)
def vfs_normpath(path: str) -> str:
"""Normalize path from posixpath.py, eliminating double slashes, etc.
Args:
path: str. Path that is to be normalized.
Returns:
str. Path if it is not null else a dot string.
"""
return os.path.normpath(path)
def require_valid_name(
name: str, name_type: str, allow_empty: bool = False
) -> None:
"""Generic name validation.
Args:
name: str. The name to validate.
name_type: str. A human-readable string, like 'the exploration title' or
'a state name'. This will be shown in error messages.
allow_empty: bool. If True, empty strings are allowed.
Raises:
ValidationError. Name isn't a string.
ValidationError. The length of the name_type isn't between
1 and 50.
ValidationError. Name starts or ends with whitespace.
ValidationError. Adjacent whitespace in name_type isn't collapsed.
ValidationError. Invalid character is present in name.
"""
if not isinstance(name, str):
raise ValidationError('%s must be a string.' % name)
if allow_empty and name == '':
return
# This check is needed because state names are used in URLs and as ids
# for statistics, so the name length should be bounded above.
if len(name) > 50 or len(name) < 1:
raise ValidationError(
'The length of %s should be between 1 and 50 '
'characters; received %s' % (name_type, name))
if name[0] in string.whitespace or name[-1] in string.whitespace:
raise ValidationError(
'Names should not start or end with whitespace.')
if re.search(r'\s\s+', name):
raise ValidationError(
'Adjacent whitespace in %s should be collapsed.' % name_type)
for character in constants.INVALID_NAME_CHARS:
if character in name:
raise ValidationError(
r'Invalid character %s in %s: %s' %
(character, name_type, name))
def require_valid_url_fragment(
name: str, name_type: str, allowed_length: int
) -> None:
"""Generic URL fragment validation.
Args:
name: str. The name to validate.
name_type: str. A human-readable string, like 'topic url fragment'.
This will be shown in error messages.
allowed_length: int. Allowed length for the name.
Raises:
ValidationError. Name is not a string.
ValidationError. Name is empty.
ValidationError. The length of the name_type is not correct.
ValidationError. Invalid character is present in the name.
"""
if not isinstance(name, str):
raise ValidationError(
'%s field must be a string. Received %s.' % (name_type, name))
if name == '':
raise ValidationError(
'%s field should not be empty.' % name_type)
if len(name) > allowed_length:
raise ValidationError(
'%s field should not exceed %d characters, '
'received %s.' % (name_type, allowed_length, name))
if not re.match(constants.VALID_URL_FRAGMENT_REGEX, name):
raise ValidationError(
'%s field contains invalid characters. Only lowercase words'
' separated by hyphens are allowed. Received %s.' % (
name_type, name))
def require_valid_thumbnail_filename(thumbnail_filename: str) -> None:
"""Generic thumbnail filename validation.
Args:
thumbnail_filename: str. The thumbnail filename to validate.
Raises:
ValidationError. Thumbnail filename is not a string.
ValidationError. Thumbnail filename does start with a dot.
ValidationError. Thumbnail filename includes slashes
or consecutive dots.
ValidationError. Thumbnail filename does not include an extension.
ValidationError. Thumbnail filename extension is not svg.
"""
if thumbnail_filename is not None:
if not isinstance(thumbnail_filename, str):
raise ValidationError(
'Expected thumbnail filename to be a string, received %s'
% thumbnail_filename)
if thumbnail_filename.rfind('.') == 0:
raise ValidationError(
'Thumbnail filename should not start with a dot.')
if '/' in thumbnail_filename or '..' in thumbnail_filename:
raise ValidationError(
'Thumbnail filename should not include slashes or '
'consecutive dot characters.')
if '.' not in thumbnail_filename:
raise ValidationError(
'Thumbnail filename should include an extension.')
dot_index = thumbnail_filename.rfind('.')
extension = thumbnail_filename[dot_index + 1:].lower()
if extension != 'svg':
raise ValidationError(
'Expected a filename ending in svg, received %s' %
thumbnail_filename)
def require_valid_image_filename(image_filename: str) -> None:
"""Generic image filename validation.
Args:
image_filename: str. The image filename to validate.
Raises:
ValidationError. Image filename is not a string.
ValidationError. Image filename does start with a dot.
ValidationError. Image filename includes slashes
or consecutive dots.
ValidationError. Image filename does not include an extension.
"""
if image_filename is not None:
if not isinstance(image_filename, str):
raise ValidationError(
'Expected image filename to be a string, received %s'
% image_filename)
if image_filename.rfind('.') == 0:
raise ValidationError(
'Image filename should not start with a dot.')
if '/' in image_filename or '..' in image_filename:
raise ValidationError(
'Image filename should not include slashes or '
'consecutive dot characters.')
if '.' not in image_filename:
raise ValidationError(
'Image filename should include an extension.')
def require_valid_meta_tag_content(meta_tag_content: str) -> None:
"""Generic meta tag content validation.
Args:
meta_tag_content: str. The meta tag content to validate.
Raises:
ValidationError. Meta tag content is not a string.
ValidationError. Meta tag content is longer than expected.
"""
if not isinstance(meta_tag_content, str):
raise ValidationError(
'Expected meta tag content to be a string, received %s'
% meta_tag_content)
if len(meta_tag_content) > constants.MAX_CHARS_IN_META_TAG_CONTENT:
raise ValidationError(
'Meta tag content should not be longer than %s characters.'
% constants.MAX_CHARS_IN_META_TAG_CONTENT)
def require_valid_page_title_fragment_for_web(
page_title_fragment_for_web: str
) -> None:
"""Generic page title fragment validation.
Args:
page_title_fragment_for_web: str. The page title fragment to validate.
Raises:
ValidationError. Page title fragment is not a string.