-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtility.py
More file actions
82 lines (72 loc) · 2.83 KB
/
Utility.py
File metadata and controls
82 lines (72 loc) · 2.83 KB
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
import base64
import gzip
import json
import urllib.request
from typing import List, Any, Dict
class Utility(object):
@staticmethod
def format_output_string(output: List[Any]) -> str:
"""
Format a list of tuples or strings to be evenly aligned.
The list can be made up of strings or tuples of type (str, str). All tuples will be right aligned to the longest string in the tuples.
When there is just a string in the list, it will be left untouched.
:param output: list containing strings and tuples of type (str, str)
:return: formatted output string
"""
character_count = 0
out = list()
# determine length
for st in output:
if type(st) == tuple:
if len(st[0]) > character_count:
character_count = len(st[0])
# format
for st in output:
if type(st) == tuple:
out.append(st[0].rjust(character_count) + st[1])
else:
out.append(st)
return "\n".join(out)
# noinspection PyBroadException
@staticmethod
def get_loadouts_from_string(s: str) -> List[Dict[str, any]]:
r = list()
if not s:
return r
# 1st possibility: one loadout event spanning over multiple lines, multiple loadout events or SLEF
try:
j = json.loads(s)
if type(j) == dict:
return [j]
else:
return j
except Exception:
# not a single json
pass
# multiple entries then
try:
lines = s.split("\n")
for line in lines:
if line.startswith("{"):
# could be json
r.append(json.loads(line))
else:
if line.startswith("https://"):
text = line.split("=")[1]
else:
# maybe someone removed the first part of the URLs and left the compressed loadout event
text = line
r.append(json.loads(gzip.decompress(base64.b64decode(urllib.request.unquote_to_bytes(text))).decode("utf-8")))
except Exception:
pass
if len(r) == 0:
raise RuntimeError("Not a valid import. See readme for further details.")
return r
@staticmethod
def create_export_url(d: Dict[str, Any], url: str) -> str:
loadout_gzip = gzip.compress(json.dumps(d).encode("utf-8"))
loadout_b64 = base64.urlsafe_b64encode(loadout_gzip).decode("utf-8").replace('=', '%3D')
return url.format(loadout_b64)
@staticmethod
def create_slef_data(d: Dict[str, Any], url: str) -> Dict[str, Any]:
return d