nextcloud.response.OCSResponse.__repr__()   A
last analyzed

Complexity

Conditions 2

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 2
nop 1
1
# -*- coding: utf-8 -*-
2
from json import JSONDecodeError
3
4
from .api_wrappers.webdav import WebDAVStatusCodes
5
6
7
class NextCloudResponse(object):
8
9
    def __init__(self, response, json_output=True, data=None):
10
        self.raw = response
11
        if not data:
12
            self.data = response.json() if json_output else response.content.decode("UTF-8")
13
        else:
14
            self.data = data
15
16
17
class WebDAVResponse(NextCloudResponse):
18
    """ Response class for WebDAV api methods """
19
20
    METHODS_SUCCESS_CODES = {
21
        "PROPFIND": [WebDAVStatusCodes.MULTISTATUS_CODE],
22
        "PROPPATCH": [WebDAVStatusCodes.MULTISTATUS_CODE],
23
        "REPORT": [WebDAVStatusCodes.MULTISTATUS_CODE],
24
        "MKCOL": [WebDAVStatusCodes.CREATED_CODE],
25
        "COPY": [WebDAVStatusCodes.CREATED_CODE, WebDAVStatusCodes.NO_CONTENT_CODE],
26
        "MOVE": [WebDAVStatusCodes.CREATED_CODE, WebDAVStatusCodes.NO_CONTENT_CODE],
27
        "PUT": [WebDAVStatusCodes.CREATED_CODE],
28
        "DELETE": [WebDAVStatusCodes.NO_CONTENT_CODE]
29
    }
30
31
    def __init__(self, response, data=None):
32
        super(WebDAVResponse, self).__init__(response=response, data=data, json_output=False)
33
        request_method = response.request.method
34
        self.is_ok = False
35
        if request_method in self.METHODS_SUCCESS_CODES:
36
            self.is_ok = response.status_code in self.METHODS_SUCCESS_CODES[request_method]
37
38
    def __repr__(self):
39
        is_ok_str = "OK" if self.is_ok else "Failed"
40
        return "<OCSResponse: Status: {}>".format(is_ok_str)
41
42
43
class OCSResponse(NextCloudResponse):
44
    """ Response class for OCS api methods """
45
46
    def __init__(self, response, json_output=True, success_code=None):
47
        self.raw = response
48
        self.is_ok = None
49
50
        if json_output:
51
            try:
52
                self.full_data = response.json()
53
                self.meta = self.full_data['ocs']['meta']
54
                self.status_code = self.full_data['ocs']['meta']['statuscode']
55
                self.data = self.full_data['ocs']['data']
56
                if success_code:
57
                    self.is_ok = self.full_data['ocs']['meta']['statuscode'] == success_code
58
            except JSONDecodeError:
59
                self.is_ok = False
60
                self.data = {'message': 'Unable to parse JSON response'}
61
        else:
62
            self.data = response.content.decode("UTF-8")
63
64
    def __repr__(self):
65
        is_ok_str = "OK" if self.is_ok else "Failed"
66
        return "<OCSResponse: Status: {}>".format(is_ok_str)
67