renderers.py 2.09 KB
Newer Older
1
2
3
4
import xml.etree.ElementTree as ET

from rest_framework import renderers

5
6
import funkwhale_api

7

8
9
def structure_payload(data):
    payload = {
10
        "funkwhaleVersion": funkwhale_api.__version__,
11
12
        "status": "ok",
        "type": "funkwhale",
13
        "version": "1.16.0",
14
15
16
17
18
19
20
21
22
    }
    payload.update(data)
    if "detail" in payload:
        payload["error"] = {"code": 0, "message": payload.pop("detail")}
    if "error" in payload:
        payload["status"] = "failed"
    return payload


23
24
25
26
27
class SubsonicJSONRenderer(renderers.JSONRenderer):
    def render(self, data, accepted_media_type=None, renderer_context=None):
        if not data:
            # when stream view is called, we don't have any data
            return super().render(data, accepted_media_type, renderer_context)
28
        final = {"subsonic-response": structure_payload(data)}
29
30
31
32
        return super().render(final, accepted_media_type, renderer_context)


class SubsonicXMLRenderer(renderers.JSONRenderer):
Eliot Berriot's avatar
Eliot Berriot committed
33
    media_type = "text/xml"
34
35
36
37
38

    def render(self, data, accepted_media_type=None, renderer_context=None):
        if not data:
            # when stream view is called, we don't have any data
            return super().render(data, accepted_media_type, renderer_context)
39
40
        final = structure_payload(data)
        final["xmlns"] = "http://subsonic.org/restapi"
Eliot Berriot's avatar
Eliot Berriot committed
41
42
43
44
        tree = dict_to_xml_tree("subsonic-response", final)
        return b'<?xml version="1.0" encoding="UTF-8"?>\n' + ET.tostring(
            tree, encoding="utf-8"
        )
45
46
47
48
49
50
51
52
53
54
55


def dict_to_xml_tree(root_tag, d, parent=None):
    root = ET.Element(root_tag)
    for key, value in d.items():
        if isinstance(value, dict):
            root.append(dict_to_xml_tree(key, value, parent=root))
        elif isinstance(value, list):
            for obj in value:
                root.append(dict_to_xml_tree(key, obj, parent=root))
        else:
56
57
            if key == "value":
                root.text = str(value)
58
59
            elif key == "cdata_value":
                root.text = "<![CDATA[{}]]>".format(str(value))
60
61
            else:
                root.set(key, str(value))
62
    return root