You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

116 lines
3.8 KiB

  1. # Copyright 2020 Coop IT Easy SCRL fs
  2. # Robin Keunen <robin@coopiteasy.be>
  3. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
  4. import json
  5. import logging
  6. import requests
  7. from werkzeug.exceptions import BadRequest, InternalServerError, NotFound
  8. from odoo import _, api, fields, models
  9. from odoo.exceptions import AccessDenied, Warning as UserError
  10. _logger = logging.getLogger(__name__)
  11. class EMCBackend(models.Model):
  12. _name = "emc.backend"
  13. _description = "EMC Backend"
  14. name = fields.Char(string="Name", required=True)
  15. location = fields.Char(string="URL")
  16. api_key = fields.Char(string="API Key")
  17. description = fields.Text(string="Description", required=False)
  18. active = fields.Boolean(string="active", default=True)
  19. @api.model
  20. def get_backend(self):
  21. backend = self.env["emc.backend"].search([("active", "=", True)])
  22. try:
  23. backend.ensure_one()
  24. except ValueError as e:
  25. _logger.error(
  26. "One and only one backend is allowed for the Easy My Coop "
  27. "connector."
  28. )
  29. raise e
  30. return backend
  31. @api.multi
  32. def http_get(self, url, params=None, headers=None):
  33. self.ensure_one()
  34. headers = self._add_api_key(headers)
  35. if url.startswith("/"):
  36. url = self.location + url
  37. _logger.info("GET to {} w/ params {}".format(url, params))
  38. return requests.get(url, params=params, headers=headers)
  39. def _process_response(self, response):
  40. if response.status_code == 200:
  41. content = response.content.decode("utf-8")
  42. return json.loads(content)
  43. elif response.status_code == 400:
  44. content = response.content.decode("utf-8")
  45. raise BadRequest("%s" % content)
  46. elif response.status_code == 403:
  47. raise AccessDenied(
  48. _("You are not allowed to access this resource")
  49. )
  50. elif response.status_code == 404:
  51. raise NotFound(
  52. _("Resource not found %s on server" % response.status_code)
  53. )
  54. else: # 500 et al.
  55. content = response.content.decode("utf-8")
  56. raise InternalServerError(_("%s" % content))
  57. @api.multi
  58. def http_get_content(self, url, params=None, headers=None):
  59. self.ensure_one()
  60. response = self.http_get(url, params=params, headers=headers)
  61. return self._process_response(response)
  62. @api.multi
  63. def http_post(self, url, data, headers=None):
  64. self.ensure_one()
  65. headers = self._add_api_key(headers)
  66. if url.startswith("/"):
  67. url = self.location + url
  68. _logger.info("POST to %s" % url)
  69. return requests.post(url, json=data, headers=headers)
  70. def http_post_content(self, url, data, headers=None):
  71. self.ensure_one()
  72. response = self.http_post(url, data, headers=headers)
  73. return self._process_response(response)
  74. @api.multi
  75. def _add_api_key(self, headers):
  76. self.ensure_one()
  77. key_dict = {"API-KEY": self.api_key}
  78. if headers:
  79. headers.update(key_dict)
  80. else:
  81. headers = key_dict
  82. return headers
  83. @api.multi
  84. def action_ping(self):
  85. self.ensure_one()
  86. url = self.location + "/api/ping/test"
  87. try:
  88. response = requests.get(url)
  89. except Exception as e:
  90. _logger.error(e)
  91. raise UserError(_("Failed to connect to backend: %s" % str(e)))
  92. if response.status_code == 200:
  93. content = json.loads(response.content.decode("utf-8"))
  94. raise UserError(_("Success: %s") % content["message"])
  95. else:
  96. raise UserError(
  97. _("Failed to connect to backend: %s" % str(response.content))
  98. )