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.

78 lines
2.2 KiB

  1. # coding: utf-8
  2. # Copyright 2017 OpenSynergy Indonesia <https://opensynergy-indonesia.com>
  3. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
  4. from openerp import api, models, fields
  5. from ..models.keychain import TWILIO_KEYCHAIN_NAMESPACE
  6. from twilio.rest import Client
  7. import logging
  8. _logger = logging.getLogger(__name__)
  9. class SmsClient(models.Model):
  10. _inherit = "sms.gateway"
  11. method = fields.Selection(
  12. selection_add=[
  13. ("twilio", "TWILIO"),
  14. ],
  15. )
  16. @api.multi
  17. def _provider_get_provider_conf(self):
  18. for rec in self:
  19. keychain = rec.env["keychain.account"]
  20. if rec._check_permissions():
  21. retrieve = keychain.suspend_security().retrieve
  22. else:
  23. retrieve = keychain.retrieve
  24. accounts = retrieve(
  25. [["namespace", "=", TWILIO_KEYCHAIN_NAMESPACE]])
  26. return accounts[0]
  27. class SmsSms(models.Model):
  28. _inherit = "sms.sms"
  29. @api.model
  30. def _prepare_twilio(self):
  31. keychain_account = self.gateway_id._provider_get_provider_conf()
  32. params = {
  33. "twilio_account": keychain_account["login"],
  34. "twilio_token": keychain_account.get_password(),
  35. "from": self.gateway_id.from_provider,
  36. "to": self._convert_to_e164(self.mobile),
  37. "message": self.message,
  38. }
  39. if self.nostop:
  40. params["noStop"] = 1
  41. if self.deferred:
  42. params["deferred"] = self.deferred
  43. if self.classes:
  44. params["class"] = self.classes
  45. if self.tag:
  46. params["tag"] = self.tag
  47. if self.coding:
  48. params["smsCoding"] = self.coding
  49. return params
  50. @api.model
  51. def _convert_to_e164(self, erp_number):
  52. to_dial_number = erp_number.replace(u"\xa0", u"")
  53. return to_dial_number
  54. @api.multi
  55. def _send_twilio(self):
  56. self.ensure_one()
  57. params = self._prepare_twilio()
  58. client = Client(
  59. params["twilio_account"],
  60. params["twilio_token"],
  61. )
  62. client.messages.create(
  63. to=params["to"],
  64. from_=params["from"],
  65. body=params["message"]
  66. )