-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.py
365 lines (323 loc) · 10.6 KB
/
mod.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
#!/usr/bin/env python3
#
# Copyright 2016 Red Hat, Inc.
#
# Authors:
# Fam Zheng <famz@redhat.com>
#
# This work is licensed under the MIT License. Please see the LICENSE file or
# http://opensource.org/licenses/MIT.
import imp
import os
import sys
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.http import HttpResponseRedirect
from django.template import Template, Context
from django.views.decorators.http import require_POST
import traceback
import configparser
import schema
class HttpResponseSeeOther(HttpResponseRedirect):
status_code = 303
def www_authenticated_op(func):
def inner(request, *args, **kwargs):
if not request.user.is_authenticated:
raise PermissionDenied
func(request, *args, **kwargs)
return HttpResponseSeeOther(request.POST["next"])
return require_POST(inner)
class PatchewModule:
"""Module base class"""
name = None # The name of the module, must be unique
default_config = "" # The default config string
project_config_schema = None
def get_model(self):
# ALways read from DB to accept configuration update in-flight
return _module_init_config(self.__class__)
def get_config_raw(self):
return self.get_model().config or ""
def get_config_obj(self):
config = configparser.ConfigParser()
config.read_string(self.get_config_raw())
return config
def get_config(self, section, field, getmethod="get", default=None):
cfg = self.get_config_obj()
if not section in cfg.sections():
return default
if field in dict(cfg.items(section)):
return getattr(cfg, getmethod)(section, field)
else:
return default
def _render_template(self, request, project, tmpl, **data):
data["project"] = project
data["module"] = self
return Template(tmpl).render(Context(data))
def _build_map_scm(self, request, project, prefix, config, scm):
schema_html = self._build_one(request, project, "", {}, scm.item)
item = {"html": schema_html}
config = config or {}
items = [
{
"name": name,
"html": self._build_one(
request, project, prefix + "." + name, value, scm.item
),
}
for name, value in config.items()
]
return self._render_template(
request,
project,
TMPL_MAP,
schema=scm,
item_schema=scm.item,
prefix=prefix,
items=items,
item=item,
)
def _build_array_scm(self, request, project, prefix, config, scm):
config = config or {}
members = [
self._build_one(
request, project, prefix + "." + x.name, config.get(x.name), x
)
for x in scm.members
]
return self._render_template(
request, project, TMPL_ARRAY, schema=scm, members=members, prefix=prefix
)
def _build_string_scm(self, request, project, prefix, config, scm):
return self._render_template(
request,
project,
TMPL_STRING,
schema=scm,
name=scm.name,
prefix=prefix,
value=config or "",
)
def _build_integer_scm(self, request, project, prefix, config, scm):
return self._render_template(
request,
project,
TMPL_INTEGER,
schema=scm,
name=scm.name,
prefix=prefix,
value=config or 0,
)
def _build_boolean_scm(self, request, project, prefix, config, scm):
return self._render_template(
request,
project,
TMPL_BOOLEAN,
schema=scm,
name=scm.name,
prefix=prefix,
value=config or False,
)
def _build_enum_scm(self, request, project, prefix, config, scm):
return self._render_template(
request,
project,
TMPL_ENUM,
schema=scm,
name=scm.name,
prefix=prefix,
value=config,
)
def _build_one(self, request, project, prefix, config, scm):
if type(scm) == schema.MapSchema:
return self._build_map_scm(request, project, prefix, config, scm)
elif type(scm) == schema.StringSchema:
return self._build_string_scm(request, project, prefix, config, scm)
elif type(scm) == schema.IntegerSchema:
return self._build_integer_scm(request, project, prefix, config, scm)
elif type(scm) == schema.BooleanSchema:
return self._build_boolean_scm(request, project, prefix, config, scm)
elif type(scm) == schema.EnumSchema:
return self._build_enum_scm(request, project, prefix, config, scm)
elif type(scm) == schema.ArraySchema:
return self._build_array_scm(request, project, prefix, config, scm)
assert False
def build_config_html(self, request, project):
assert isinstance(self.project_config_schema, schema.ArraySchema)
scm = self.project_config_schema
config = self.get_project_config(project)
return self._build_one(request, project, scm.name, config, scm)
def get_project_config(self, project):
return project.config.get(self.project_config_schema.name, {})
_loaded_modules = {}
def _module_init_config(cls):
from api.models import Module
mod, _ = Module.objects.get_or_create(
name=cls.name, defaults={"config": cls.default_config.strip()}
)
return mod
def load_modules():
_module_path = settings.MODULE_DIR
sys.path.append(_module_path)
for f in os.listdir(_module_path):
if f.endswith(".py"):
pn = f[: -len(".py")]
try:
imp.load_source(pn, os.path.join(_module_path, f))
except:
traceback.print_exc()
for cls in PatchewModule.__subclasses__():
if cls.name not in _loaded_modules:
_loaded_modules[cls.name] = cls()
print("Loaded module:", cls.name)
def dispatch_module_hook(hook_name, **params):
for i in _loaded_modules.values():
if hasattr(i, hook_name):
try:
getattr(i, hook_name)(**params)
except:
print("Cannot invoke module hook: %s.%s" % (i, hook_name))
traceback.print_exc()
def get_module(name):
return _loaded_modules.get(name)
TMPL_STRING = """
<div class="form-group">
<label for="{{ module.name }}-input-{{ schema.name }}">{{ schema.title }}</label>
{% if schema.multiline %}
<textarea rows="10"
{% else %}
<input
{% endif %}
type="text" class="form-control project-property"
data-property-path="{{ prefix }}"
id="{{ module.name }}-input-{{ schema.name }}" {% if schema.required %}required{%endif%}
name="{{ name }}" placeholder="{{ schema.desc }}"
{% if schema.multiline %}
>{{ value | default_if_none:schema.default }}</textarea>
{% else %}
value="{{ value | default_if_none:"" }}">
{% endif %}
</div>
"""
TMPL_INTEGER = """
<div class="form-group">
<label for="{{ module.name }}-input-{{ schema.name }}">{{ schema.title }}</label>
<input type="number" class="form-control project-property"
data-property-path="{{ prefix }}"
id="{{ module.name }}-input-{{ schema.name }}" {% if schema.required %}required{%endif%}
name="{{ name }}" placeholder="{{ schema.desc }}"
{% if schema.multiline %}
>{{ value | default_if_none:schema.default }}</textarea>
{% else %}
value="{{ value | default_if_none:schema.default }}">
{% endif %}
</div>
"""
TMPL_BOOLEAN = """
<div class="form-check">
<label>
<input class="project-property" type="checkbox" name="{{ name }}"
data-property-path="{{ prefix }}"
{% if value == None %}
{% if schema.default %}
checked
{% endif %}
{% elif value %}
checked
{% endif %}
>
<span title="{{ schema.desc }}">{{ schema.title }}</span>
</label>
</div>
"""
TMPL_ENUM_DESC = """
<div class="well" style="margin-top: 10px;">
<h4>Available variables in template</h4>
{% for k, v in desc.items %}
<p><strong>{{ k }}</strong>: {{ v }}</p>
{% endfor %}
</div>
"""
TMPL_ENUM = (
"""
<div class="form-group">
<label for="{{ module.name }}-input-{{ schema.name }}">{{ schema.title }}</label>
<select class="form-control project-property"
id="{{ module.name }}-input-{{ schema.name }}"
data-property-path="{{ prefix }}"
onchange="enum_change(this)"
{% if schema.required %}required{%endif%}
name="{{ name }}">
<option disabled selected value=""> -- select an event type -- </option>
{% for opt in schema.enums %}
{% if opt == value %}
<option selected value="{{ opt }}">{{ opt }}</option>
{% else %}
<option value="{{ opt }}">{{ opt }}</option>
{% endif %}
{% endfor %}
</select>
<div class="form-group enum-desc">
{% for opt, desc in schema.enums.items %}
{% if opt == value %}
"""
+ TMPL_ENUM_DESC
+ """
{% endif %}
{% endfor %}
</div>
{% for opt, desc in schema.enums.items %}
<div class="d-none enum-desc-{{ opt }}">
"""
+ TMPL_ENUM_DESC
+ """
</div>
{% endfor %}
</div>
"""
)
TMPL_ARRAY = """
{% for schema in members %}
{{ schema }}
{% endfor %}
"""
TMPL_MAP_ITEM = """
<div class="item card" data-property-prefix="{{ prefix }}{% if item.name %}.{{ item.name }}{% endif %}">
<div class="item-heading card-header card-toggler" onclick="return patchew_toggler_onclick(this)">
{{ item_schema.title }}
<strong class="item-name">{{ item.name }}</strong>
</div>
<div class="card-body card-collapse collapse" aria-expanded="false">
{{ item.html }}
<div class="form-group">
<button type="button"
class="btn btn-danger" onclick="map_delete_item(this)">
Delete
</button>
</div>
</div>
</div>
"""
TMPL_MAP = (
"""
<div>
<script class="item-template" type="text/x-custom-template">
"""
+ TMPL_MAP_ITEM
+ """
</script>
<div class="items">
{% for item in items %}
"""
+ TMPL_MAP_ITEM
+ """
{% endfor %}
</div>
<div class="form-group">
<button type="button"
class="btn btn-info" onclick="map_add_item(this)">
Add {{ item_schema.title }}
</button>
</div>
</div>
"""
)