__init__.py 7.02 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# ##############################################################################
#  Author: echel0n <[email protected]>
#  URL: https://sickrage.ca/
#  Git: https://git.sickrage.ca/SiCKRAGE/sickrage.git
#  -
#  This file is part of SiCKRAGE.
#  -
#  SiCKRAGE is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#  -
#  SiCKRAGE is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#  -
#  You should have received a copy of the GNU General Public License
#  along with SiCKRAGE.  If not, see <http://www.gnu.org/licenses/>.
# ##############################################################################
echel0n's avatar
echel0n committed
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
import json
import traceback
from abc import ABC

from apispec import APISpec
from apispec.exceptions import APISpecError
from apispec.ext.marshmallow import MarshmallowPlugin
from apispec_webframeworks.tornado import TornadoPlugin
from tornado.escape import to_basestring
from tornado.web import HTTPError

import sickrage
from sickrage.core.helpers import get_external_ip, get_internal_ip
from sickrage.core.webserver.handlers.base import BaseHandler


class APIBaseHandler(BaseHandler, ABC):
    def prepare(self):
        super(APIBaseHandler, self).prepare()

        method_name = self.request.method.lower()
        if method_name == 'options':
            return

        certs = sickrage.app.auth_server.certs()
        auth_header = self.request.headers.get('Authorization')

        if auth_header:
            if 'bearer' in auth_header.lower():
                try:
                    token = auth_header.strip('Bearer').strip()
                    decoded_auth_token = sickrage.app.auth_server.decode_token(token, certs)

                    if not sickrage.app.config.user.sub_id:
                        sickrage.app.config.user.sub_id = decoded_auth_token.get('sub')
                        sickrage.app.config.save()

                    if sickrage.app.config.user.sub_id != decoded_auth_token.get('sub'):
                        return self.send_error(401, error='user is not authorized')

                    if sickrage.app.config.general.enable_sickrage_api and not sickrage.app.api.token:
                        exchanged_token = sickrage.app.auth_server.token_exchange(token)
                        if exchanged_token:
                            sickrage.app.api.token = exchanged_token

                    internal_connections = "{}://{}:{}{}".format(self.request.protocol,
                                                                 get_internal_ip(),
                                                                 sickrage.app.config.general.web_port,
                                                                 sickrage.app.config.general.web_root)

                    external_connections = "{}://{}:{}{}".format(self.request.protocol,
                                                                 get_external_ip(),
                                                                 sickrage.app.config.general.web_port,
                                                                 sickrage.app.config.general.web_root)

                    connections = ','.join([internal_connections, external_connections])

                    if sickrage.app.config.general.server_id and not sickrage.app.api.account.update_server(sickrage.app.config.general.server_id, connections):
                        sickrage.app.config.general.server_id = ''

                    if not sickrage.app.config.general.server_id:
                        server_id = sickrage.app.api.account.register_server(connections)
                        if server_id:
                            sickrage.app.config.general.server_id = server_id
                            sickrage.app.config.save()

                    self.current_user = decoded_auth_token
                except Exception:
                    return self.send_error(401, error='failed to decode token')
            else:
                return self.send_error(401, error='invalid authorization request')
        else:
            return self.send_error(401, error='authorization header missing')

    def get_current_user(self):
        return self.current_user

    def write_error(self, status_code, **kwargs):
        self.set_header('Content-Type', 'application/json')
        self.set_status(status_code)

        if status_code == 500:
            excp = kwargs['exc_info'][1]
            tb = kwargs['exc_info'][2]
            stack = traceback.extract_tb(tb)
            clean_stack = [i for i in stack if i[0][-6:] != 'gen.py' and i[0][-13:] != 'concurrent.py']
            error_msg = '{}\n  Exception: {}'.format(''.join(traceback.format_list(clean_stack)), excp)

            sickrage.app.log.debug(error_msg)
        else:
            error_msg = kwargs.get('reason', '') or kwargs.get('error', '')

        self.write_json({'error': error_msg})

    def set_default_headers(self):
        super(APIBaseHandler, self).set_default_headers()
        self.set_header('Content-Type', 'application/json')

    def write_json(self, response):
        self.write(json.dumps(response))

    def _validate_schema(self, schema, arguments):
        return schema().validate({k: to_basestring(v[0]) if len(v) <= 1 else to_basestring(v) for k, v in arguments.items()})

    def _parse_value(self, value, func):
        if value is not None:
            try:
                return func(value)
            except ValueError:
                raise HTTPError(400, f'Invalid value {value!r}')

    def _parse_boolean(self, value):
        if isinstance(value, str):
            return value.lower() == 'true'
        return self._parse_value(value, bool)

    def generate_swagger_json(self, handlers, api_version):
        """Automatically generates Swagger spec file based on RequestHandler
        docstrings and returns it.
        """

        spec = APISpec(
            title="SiCKRAGE App API",
            version=api_version,
            openapi_version="3.0.2",
            info={'description': "Documentation for SiCKRAGE App API"},
            plugins=[TornadoPlugin(), MarshmallowPlugin()],
        )

        for handler in handlers:
            try:
                spec.path(urlspec=handler)
            except APISpecError:
                pass

        return spec.to_dict()


class PingHandler(APIBaseHandler, ABC):
    def get(self):
        return self.write_json({'message': 'pong'})


class SwaggerDotJsonHandler(APIBaseHandler, ABC):
    def initialize(self, api_handlers, api_version):
        super(SwaggerDotJsonHandler, self).initialize()
        self.api_handlers = sickrage.app.wserver.handlers[api_handlers]
        self.api_version = api_version

    def get(self):
        """ Get swagger.json """
        return self.write_json(self.generate_swagger_json(self.api_handlers, self.api_version))