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.

104 lines
3.7 KiB

  1. # -*- encoding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # Copyright (C) 2015 Compassion CH (http://www.compassion.ch)
  5. # Releasing children from poverty in Jesus' name
  6. # @author: Roman Zoller
  7. #
  8. # The licence is in the file __openerp__.py
  9. #
  10. ##############################################################################
  11. from openerp import models, fields, api, exceptions, _
  12. from openerp.tools.config import config
  13. import json
  14. import re
  15. import logging
  16. _logger = logging.getLogger(__name__)
  17. try:
  18. import sendgrid
  19. except ImportError:
  20. _logger.error("ImportError raised while loading module.")
  21. _logger.debug("ImportError details:", exc_info=True)
  22. class SendgridTemplate(models.Model):
  23. """ Reference to a template available on the SendGrid user account. """
  24. _name = 'sendgrid.template'
  25. ##########################################################################
  26. # FIELDS #
  27. ##########################################################################
  28. name = fields.Char()
  29. remote_id = fields.Char(readonly=True)
  30. html_content = fields.Html(readonly=True)
  31. plain_content = fields.Text(readonly=True)
  32. detected_keywords = fields.Char(compute='_compute_keywords')
  33. def _compute_keywords(self):
  34. for template in self:
  35. if template.html_content:
  36. keywords = template.get_keywords()
  37. self.detected_keywords = ';'.join(keywords)
  38. @api.model
  39. def update(self):
  40. api_key = config.get('sendgrid_api_key')
  41. if not api_key:
  42. raise exceptions.Warning(
  43. 'ConfigError',
  44. _('Missing sendgrid_api_key in conf file'))
  45. sg = sendgrid.SendGridAPIClient(apikey=api_key)
  46. template_client = sg.client.templates
  47. msg = template_client.get().body
  48. result = json.loads(msg)
  49. for template in result.get("templates", list()):
  50. id = template["id"]
  51. msg = template_client._(id).get().body
  52. template_versions = json.loads(msg)['versions']
  53. for version in template_versions:
  54. if version['active']:
  55. template_vals = version
  56. break
  57. else:
  58. continue
  59. vals = {
  60. "remote_id": id,
  61. "name": template["name"],
  62. "html_content": template_vals["html_content"],
  63. "plain_content": template_vals["plain_content"],
  64. }
  65. record = self.search([('remote_id', '=', id)])
  66. if record:
  67. record.write(vals)
  68. else:
  69. self.create(vals)
  70. return True
  71. def get_keywords(self):
  72. """ Search in the Sendgrid template for keywords included with the
  73. following syntax: {keyword_name} and returns the list of keywords.
  74. keyword_name shouldn't be longer than 20 characters and only contain
  75. alphanumeric characters (underscore is allowed).
  76. You can replace the substitution prefix and suffix by adding values
  77. in the system parameters
  78. - mail_sendgrid.substitution_prefix
  79. - mail_sendgrid.substitution_suffix
  80. """
  81. self.ensure_one()
  82. params = self.env['ir.config_parameter']
  83. prefix = params.search([
  84. ('key', '=', 'mail_sendgrid.substitution_prefix')
  85. ]).value or '{'
  86. suffix = params.search([
  87. ('key', '=', 'mail_sendgrid.substitution_suffix')
  88. ]) or '}'
  89. pattern = prefix + r'\w{0,20}' + suffix
  90. return list(set(re.findall(pattern, self.html_content)))