-
Notifications
You must be signed in to change notification settings - Fork 1
/
generator.py
56 lines (43 loc) · 1.87 KB
/
generator.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
""" Compact OwnCloud/NextCloud WebDAV client generator classes
Author: hevp
"""
from lxml import etree
from common import error, getValueByTagReference
class GeneratorFactory():
@staticmethod
def getGenerator(data, options):
return XMLGenerator(options)
class Generator():
def __init__(self, data):
self.data = data
def getContentType(self):
return 'text/plain'
class XMLGenerator(Generator):
def getContentType(self):
return 'application/xml'
def _getXMLTag(self, tag, nsmap):
if ':' in tag:
tags = tag.split(':')
tag = "{%s}%s" % (nsmap[tags[0]], tags[1])
return tag
def generate(self, data, element=None):
NSMAP = {"d": "DAV:", "oc": "http://owncloud.org/ns", "nc": "http://nextcloud.org/ns"}
try:
# create the element itself
xml = etree.Element(self._getXMLTag(data["root"], NSMAP), nsmap=NSMAP) if element is None else element
# create any children recursively
for k, v in (data["elements"].items() if element is None else data.items()):
sub = etree.SubElement(xml, self._getXMLTag(k, NSMAP), nsmap=NSMAP)
if type(v) is dict:
self.generate(v, sub)
elif type(v) is list:
for value in v:
lk = getValueByTagReference(value.keys()[0], self.data)
lv = getValueByTagReference(value.values()[0], self.data)
prop = etree.SubElement(sub, self._getXMLTag(lk, NSMAP), nsmap=NSMAP)
prop.text = getValueByTagReference(lv, self.data)
else:
sub.text = getValueByTagReference(v, self.data)
except Exception as e:
error(f"XML generation failed: {e} ", 1)
return etree.tostring(xml).decode('utf-8')