-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathhelpers.py
245 lines (197 loc) · 8.13 KB
/
helpers.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
import base64
import functools
import secrets
import string
from lxml import etree
from models import Shops, CategoryTypes
def generate_response_dict(passed_dict) -> dict:
passed_dict["apiStatus"] = {"code": 0}
passed_dict["version"] = 1
return passed_dict
def response():
def decorator(func):
@functools.wraps(func)
def serialization_wrapper(*args, **kwargs):
returned_value = func(*args, **kwargs)
# Ensure we are truly dealing with a dictionary.
if isinstance(returned_value, dict):
# Insert common elements.
returned_value = generate_response_dict(returned_value)
# Serialize to an ETree.
elements = dict_to_etree("response", returned_value)
# We now must convert from ETree to actual XML we can respond with.
return etree.tostring(
elements,
encoding="shift-jis",
xml_declaration=False,
pretty_print=True,
)
else:
# We only apply XML operations to dicts.
return returned_value
return serialization_wrapper
return decorator
def multiple_root_nodes():
"""
Nintendo makes questionable decisions. This is a fact.
Some of them one may consider somewhat justified, based on development
time and constraint.
Consider the following C pseudocode:
int index = 0;
int count = GetChildNodeCount(responseNode);
while (index < count - 1) {
// [...]
}
Nintendo loops through the count of all response codes.
As having apiStatus -> code and version normally
would mean response has a child count of 2 and other restaurants,
they violate every XML standard known to humankind and parse it separately.
It would not hurt them to have put the data inside of a separate node.
It would not hurt them to subtract 2 should they require "response" for unknown standards.
Even worse, this is Wii-specific, as none of their mobile applications
(iPhone OS 3.1 or Android 2.2, earliest found) rely on any of this functionality.
Yet, here we are.
We append such manually, as they use this syntax in multiple locations.
"""
def decorator(func):
@functools.wraps(func)
def serialization_wrapper(*args, **kwargs):
returned_value = func(*args, **kwargs)
# Only operate on dictionaries.
if isinstance(returned_value, dict):
# Insert common elements.
returned_value = generate_response_dict(returned_value)
working_response = b""
for root_name, children in returned_value.items():
elements = dict_to_etree(root_name, children)
# Convert to bytes.
working_response += etree.tostring(
elements,
encoding="shift-jis",
xml_declaration=False,
pretty_print=True,
)
# We now have all root nodes.
return working_response
else:
return returned_value
return serialization_wrapper
return decorator
def dict_to_etree(tag_name: str, d: dict) -> etree.Element:
"""Derived from https://stackoverflow.com/a/10076823."""
def _to_etree(d, root):
if d is None:
pass
elif isinstance(d, bool):
# We can only accept 0 or 1 as Nintendo's "boolean" types.
root.text = etree.CDATA("1" if d else "0")
elif isinstance(d, int):
root.text = etree.CDATA(f"{d}")
elif isinstance(d, float):
root.text = etree.CDATA(f"{d}")
elif isinstance(d, str):
root.text = etree.CDATA(d)
elif isinstance(d, bytes):
# We're going to assume this needs to be Base64 encoded.
root.text = etree.CDATA(base64.b64encode(d))
elif isinstance(d, tuple) or isinstance(d, list):
# As we're backed by K/V notation,a tuple or a list is useless.
# It should only contain our special
# RepeatedKeys and RepeatedNodes types.
should_delete = False
for v in d:
if isinstance(v, RepeatedElement):
# We'd like to duplicate this specific node in its parent.
# Now we need to obtain such.
parent_elem = root.getparent()
# Create a new sub-element in the parent with the current
# element's name.
new_elem = etree.SubElement(parent_elem, root.tag)
_to_etree(v.contents, new_elem)
should_delete = True
elif isinstance(v, RepeatedKey):
# We'd like to duplicate keys within this node.
# Retain the parent and operate on the dict.
_to_etree(v.contents, root)
else:
raise ValueError(f"invalid type {type(v).__name__} specified")
if should_delete:
# Delete ourselves once added as other repeated elements have replaced us.
root.getparent().remove(root)
elif isinstance(d, dict):
for k, v in d.items():
assert isinstance(k, str)
_to_etree(v, etree.SubElement(root, k))
else:
assert d == "invalid type", (type(d), d)
node = etree.Element(tag_name)
_to_etree(d, node)
return node
class RepeatedKey:
"""This class is intended to clarify disambiguation when converting from a dict.
Its specific behavior is to repeat its keys within a parent node.
For example:
<Parent>
<key>value</key>
<second>value</second>
<key>value</key>
<second>value</second>
</Parent>
"""
contents = {}
def __init__(self, passed_dict):
if not isinstance(passed_dict, dict):
raise ValueError("Please only pass dicts to RepeatedKey.")
self.contents = passed_dict
class RepeatedElement:
"""This class is intended to clarify disambiguation when converting from a dict.
Its specific behavior is to allow repeating an element against its parent.
For example:
<Parent>
<key>value</key>
<second>value</second>
</Parent>
<Parent>
<key>value</key>
<second>value</second>
</Parent>
"""
contents = {}
def __init__(self, passed_dict):
if not isinstance(passed_dict, dict):
raise ValueError("Please only pass dicts to RepeatedElement.")
self.contents = passed_dict
def get_restaurant(category_id: CategoryTypes):
"""This function grabs basic restaurant information recursively, so we can have
multiple restaurants without having to insert it manually in responses.py"""
# All category names and values: https://gist.github.com/SketchMaster2001/42172c8b00075b4b827fa2f78a9eb9e1
queried_categories = Shops.query.filter_by(category_code=category_id).all()
results = []
for i, restaurant in enumerate(queried_categories):
# Items must be indexed by 1.
results.append(
RepeatedElement(
{
"shopCode": restaurant.shop_code,
"homeCode": restaurant.shop_code,
"name": restaurant.name,
"catchphrase": restaurant.description,
"minPrice": 1,
"yoyaku": 1,
"activate": "on",
"waitTime": restaurant.wait_time,
"paymentList": {"athing": "Fox Card"},
"shopStatus": {
"status": {
"isOpen": 1,
}
},
}
)
)
return results
def generate_random(length: int):
# We will use this function to generate an area code for the user.
letters = string.digits
random = "".join(secrets.choice(letters) for i in range(length))
return random