-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmodel.py
199 lines (157 loc) · 5.88 KB
/
model.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
import logging
import config
from pathlib import Path
import inspect
from typing import List
import os
from functools import lru_cache, reduce, partial, wraps
class RecipeInfo():
def __init__(self, name, description, chain, reference, binaries, modify_filesystem, routes=[]):
self.name = name
self.description = description
self.chain = chain
self.routes = routes
self.reference = reference
self.binaries = binaries
self.modify_filesystem = modify_filesystem
class AceStr(str):
def __new__(cls, value):
obj = str.__new__(cls, value)
obj.index = GetCounter()
return obj
class AceBytes(bytes):
def __new__(cls, value):
obj = bytes.__new__(cls, value)
obj.index = GetCounter()
return obj
class AceFile():
def __init__(self, name: str, data: bytes):
self.name = name
self.data = data
self.index = GetCounter()
def GetCounter():
c = config.COUNTER
config.COUNTER += 1
return c
def dumpDataToFile(index, funcName, ret, retType):
filename = None
filedata = None
if 'AceBytes' in retType:
filename = "out/out_{:02d}_{}.bin".format(index, funcName)
filedata = ret
elif 'AceStr' in retType:
filename = "out/out_{:02d}_{}.txt".format(index, funcName)
filedata = bytes(ret, 'utf-8')
elif 'bytes' in retType or 'bytesarray' in retType:
filename = "out/out_{:02d}_{}.bin".format(index, funcName)
filedata = ret
elif 'str' in retType:
filename = "out/out_{:02d}_{}.txt".format(index, funcName)
filedata = bytes(ret, 'utf-8')
elif 'AceFile' in retType:
name = ret.name
# cleanup if there are any baths in it
name = name.replace('/', '_')
name = name.replace('\\', '_')
filename = "out/out_{:02d}_file_{}".format(index, name)
filedata = ret.data
if isinstance(filedata, str):
filedata = bytes(filedata, 'utf-8')
else:
logging.warn("Wrong return type: {}".format(retType))
return ret
f = open(filename, 'wb')
f.write(filedata)
f.close()
def parseFuncAceArgs(arg) -> List[str]:
s = [] # array of arguments
argType = str(type(arg))
# Stuff which has .index
if 'AceBytes' in argType or 'AceStr' in argType or 'AceFile' in argType:
s.append(str(arg.index))
# lists of data which may have .index
elif 'list' in argType:
for item in arg:
t = str(type(item))
if 'AceBytes' in t or 'AceStr' in t or 'AceFile' in t:
s.append(str(item.index))
return s
def DataTracker(func):
"""Decorator to log Ace data structures on annotated functions"""
@wraps(func) # for pdoc3
def wrapper(*args, **kwargs):
makerCounter = config.MAKER_COUNTER
config.MAKER_COUNTER += 1
# An Indent based on call stack would be useful
# Check if parents are already a make(er)
indent = ""
for n in (1, 3, 5, 7, 9, 11): # skip wrappers
parentName = inspect.stack()[n].function
if parentName.startswith('make'):
indent += " "
else:
break
allArgs = []
s = ''
# check function name special cases
funcName = str(func)
if 'readFileContent' in funcName or 'renderTemplate' in funcName:
allArgs.append(os.path.basename(str(args[0])))
elif 'makeAceRoute' in funcName:
allArgs.append(str(args[0]))
elif 'makeAceFile' in funcName:
allArgs.append(str(args[0]))
# get arguments of the function
for arg in args:
allArgs += parseFuncAceArgs(arg)
for _, arg in kwargs.items():
allArgs += parseFuncAceArgs(arg)
s += ', '.join(allArgs)
# output the data
logging.info("--[ {:02d}: {} {}({}) ".format(config.COUNTER, indent, func.__name__, s))
config.makerCallstack[makerCounter] = "--[ {:02d}: {} {}({})".format(config.COUNTER, indent, func.__name__, s)
# call the actual function
ret = func(*args, **kwargs)
# What follows: Try to print ACE information of args+ret
retType = str(type(ret))
# dont show ret for AceRoute (no further processing possible)
if 'AceRoute' in retType:
return ret
# If data is indexed, use that.
# If not, generate a new index
if 'AceBytes' in retType or 'AceStr' in retType or 'AceFile' in retType:
index = ret.index
else:
index = GetCounter()
# output the results
#logging.info("--[ {}: {} -> {}".format(config.COUNTER, indent, index))
config.makerCallstack[makerCounter] += " -> {}".format(index)
# Dump content to files
if not config.ENABLE_SAVING:
return ret
dumpDataToFile(index, func.__name__, ret, retType)
return ret
return wrapper
class AceRoute():
def __init__(self, url: str, data: bytes, info: str = '', isEntry=False, download: bool=False, downloadName: str='', downloadMime: str=None):
self.url = url
self.data = data
self.info = info
self.download = download
self.downloadName = downloadName
self.downloadMime = downloadMime
self.isEntry = isEntry
@DataTracker
def makeAceRoute(url: str, data: bytes, info: str = '', isEntry=False, download: bool=False, downloadName: str='', downloadMime: str=None):
aceRoute = AceRoute(url, data, info, isEntry, download, downloadName, downloadMime)
return aceRoute
def enableOut():
config.ENABLE_SAVING = True
def enableScanning(server):
config.ENABLE_SCANNING = server
def setListenIp(ip):
config.LISTEN_IP = ip
def setListenPort(port):
config.LISTEN_PORT = port
def enableTemplateInfo():
config.SHOW_TEMPLATE_INFO = True