|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +############################################################################## |
| 3 | +# |
| 4 | +# Copyright (C) Stephane Wirtel |
| 5 | +# Copyright (C) 2011 Nicolas Vanhoren |
| 6 | +# Copyright (C) 2011 OpenERP s.a. (<http://openerp.com>) |
| 7 | +# Copyright (C) 2018 Odoo s.a. (<http://odoo.com>). |
| 8 | +# All rights reserved. |
| 9 | +# |
| 10 | +# Redistribution and use in source and binary forms, with or without |
| 11 | +# modification, are permitted provided that the following conditions are met: |
| 12 | +# |
| 13 | +# 1. Redistributions of source code must retain the above copyright notice, this |
| 14 | +# list of conditions and the following disclaimer. |
| 15 | +# 2. Redistributions in binary form must reproduce the above copyright notice, |
| 16 | +# this list of conditions and the following disclaimer in the documentation |
| 17 | +# and/or other materials provided with the distribution. |
| 18 | +# |
| 19 | +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND |
| 20 | +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED |
| 21 | +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE |
| 22 | +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR |
| 23 | +# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES |
| 24 | +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; |
| 25 | +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND |
| 26 | +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
| 27 | +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS |
| 28 | +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 29 | +# |
| 30 | +############################################################################## |
| 31 | + |
| 32 | +import logging |
| 33 | +import requests |
| 34 | + |
| 35 | +from http import HTTPStatus |
| 36 | + |
| 37 | +from .tools import AuthenticationError, RemoteModel, _getChildLogger |
| 38 | + |
| 39 | +_logger = logging.getLogger(__name__) |
| 40 | +DEFAULT_TIMEOUT = 60 |
| 41 | + |
| 42 | + |
| 43 | +class JsonModel(RemoteModel): |
| 44 | + def __init__(self, connection, model_name): |
| 45 | + res = super().__init__(connection, model_name) |
| 46 | + self.__logger = _getChildLogger(_getChildLogger(_logger, 'object'), model_name or "") |
| 47 | + self.methods = {} |
| 48 | + self.model_methods = [] |
| 49 | + return res |
| 50 | + |
| 51 | + def __getattr__(self, method): |
| 52 | + """ |
| 53 | + Provides proxy methods that will forward calls to the model on the remote Odoo server. |
| 54 | +
|
| 55 | + :param method: The method for the linked model (search, read, write, unlink, create, ...) |
| 56 | + """ |
| 57 | + def proxy(*args, **kwargs): |
| 58 | + """ |
| 59 | + :param args: A list of values for the method |
| 60 | + """ |
| 61 | + # self.__logger.debug(args) |
| 62 | + data = kwargs |
| 63 | + if args: |
| 64 | + # Should convert args list into dict of args |
| 65 | + self._introspect() |
| 66 | + offset = 0 |
| 67 | + if method not in self.model_methods and 'ids' not in kwargs.keys(): |
| 68 | + data['ids'] = args[0] |
| 69 | + offset = 1 |
| 70 | + for i in range(offset, len(args)): |
| 71 | + if i-offset < len(self.methods[method]): |
| 72 | + data[self.methods[method][i-offset]] = args[i] |
| 73 | + else: |
| 74 | + _logger.warning(f"Method {method} called with too many arguments: {args}") |
| 75 | + |
| 76 | + result = requests.post( |
| 77 | + self._url(method), |
| 78 | + headers=self.connection.bearer_header, |
| 79 | + json=data, |
| 80 | + timeout=DEFAULT_TIMEOUT, |
| 81 | + ) |
| 82 | + |
| 83 | + if result.status_code == HTTPStatus.UNAUTHORIZED: |
| 84 | + raise AuthenticationError("Authentication failed. Please check your API key.") |
| 85 | + if result.status_code == 422: |
| 86 | + raise ValueError(f"Invalid request: {result.text} for data {data}") |
| 87 | + if result.status_code != 200: |
| 88 | + raise ValueError(f"Unexpected status code {result.status_code}: {result.text}") |
| 89 | + return result.json() |
| 90 | + return proxy |
| 91 | + |
| 92 | + def _introspect(self): |
| 93 | + if not self.methods: |
| 94 | + url = f"{self.connection.connector.url.strip('/json/2/')}/doc/{self.model_name }.json" |
| 95 | + response = requests.get(url, headers=self.connection.bearer_header) |
| 96 | + response.raise_for_status() |
| 97 | + m = response.json().get('methods', {}) |
| 98 | + self.methods = {k: tuple(m[k]['parameters'].keys()) for k in m.keys()} |
| 99 | + self.model_methods = [ k for k in m.keys() if 'model' in m[k].get('api', []) ] |
| 100 | + |
| 101 | + def read(self, *args, **kwargs): |
| 102 | + res = self.__getattr__('read')(*args, **kwargs) |
| 103 | + if len(res) == 1: |
| 104 | + return res[0] |
| 105 | + return res |
| 106 | + |
| 107 | + def _url(self, method): |
| 108 | + """ |
| 109 | + Returns the URL of the Odoo server. |
| 110 | + """ |
| 111 | + return f"{self.connection.connector.url}{self.model_name}/{method}" |
| 112 | + |
| 113 | + |
| 114 | +class Json2Connector(object): |
| 115 | + def __init__(self, hostname, port="8069"): |
| 116 | + """ |
| 117 | + Initialize by specifying the hostname and the port. |
| 118 | + :param hostname: The hostname of the computer holding the instance of Odoo. |
| 119 | + :param port: The port used by the Odoo instance for JsonRPC (default to 8069). |
| 120 | + """ |
| 121 | + if port != 80: |
| 122 | + self.url = f'http://{hostname}:{port}/json/2/' |
| 123 | + else: |
| 124 | + self.url = f'http://{hostname}/json/2/' |
| 125 | + |
| 126 | + |
| 127 | +class Json2SConnector(Json2Connector): |
| 128 | + def __init__(self, hostname, port="443"): |
| 129 | + super().__init__(hostname, port) |
| 130 | + if port != 443: |
| 131 | + self.url = f'https://{hostname}:{port}/json/2/' |
| 132 | + else: |
| 133 | + self.url = f'https://{hostname}/json/2/' |
| 134 | + |
| 135 | + |
| 136 | +class Json2Connection(object): |
| 137 | + """ |
| 138 | + A class representing a connection to an Odoo server. |
| 139 | + """ |
| 140 | + |
| 141 | + def __init__(self, connector, database, api_key): |
| 142 | + self.connector = connector |
| 143 | + self.database = database |
| 144 | + self.bearer_header = {"Authorization": f"Bearer {api_key}", 'Content-Type': 'application/json; charset=utf-8', "X-Odoo-Database": database} |
| 145 | + self.user_context = None |
| 146 | + |
| 147 | + def get_model(self, model_name): |
| 148 | + return JsonModel(self, model_name) |
| 149 | + |
| 150 | + def get_connector(self): |
| 151 | + return self.connector |
| 152 | + |
| 153 | + def get_user_context(self): |
| 154 | + """ |
| 155 | + Query the default context of the user. |
| 156 | + """ |
| 157 | + if not self.user_context: |
| 158 | + self.user_context = self.get_model('res.users').context_get() |
| 159 | + return self.user_context |
0 commit comments