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.

96 lines
3.4 KiB

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