notificationskeleton.py 2.39 KB
Newer Older
1 2
import gettext

3
import yaml
4 5


6
class NotificationSkeleton:
7
    ATTRS = ['name', 'plugin_name', 'version', 'template', 'actions', 'timeout', 'severity', 'persistent', 'explicit_dismiss']
8
    DEFAULT_ATTRS = ['timeout', 'severity', 'persistent', 'explicit_dismiss']
9

10
    def __init__(self, name, plugin_name, version, template, actions, jinja_env, timeout=None, severity='info', persistent=False, explicit_dismiss=True):
11
        self.name = name
12
        self.plugin_name = plugin_name
13
        self.version = version
14 15
        self.template = template
        self.actions = actions
16
        self.jinja_env = jinja_env
17

18 19 20
        self.timeout = timeout
        self.severity = severity
        self.persistent = persistent
21
        self.explicit_dismiss = explicit_dismiss
22

23
        self.setup_jinja_env()
24
        self.translations = {}
25

26 27 28
    def get_media_types(self):
        return self.template['supported_media']

29
    def serialize(self):
30 31 32 33
        json_data = {}

        for attr in self.ATTRS:
            json_data[attr] = getattr(self, attr)
34

35
        return json_data
36

37
    def get_skeleton_defaults(self):
38 39 40 41
        defaults = {}

        for attr in self.DEFAULT_ATTRS:
            defaults[attr] = getattr(self, attr)
42 43 44

        return defaults

45
    def get_action_cmd(self, name):
Martin Matějek's avatar
Martin Matějek committed
46
        if name in self.actions:
47 48 49
            return self.actions[name]['command']

        return None
Martin Matějek's avatar
Martin Matějek committed
50

51
    def translate_actions(self, lang):
52 53
        self._set_jinja_translation(lang)

54
        parsed = yaml.safe_load(self.jinja_plugin_template.render())
55 56 57
        return {
            pa['name']: pa['title'] for pa in parsed['actions'] if pa['name'] in self.actions
        }
58

59 60
    def setup_jinja_env(self):
        """Prepare templates for later use"""
61
        self.jinja_message_template = self.jinja_env.get_template(self.template['src'])
62

63
        plugin_template = '{}.yml'.format(self.plugin_name)
64
        self.jinja_plugin_template = self.jinja_env.get_template(plugin_template)
65

66 67
    def _set_jinja_translation(self, lang):
        self.jinja_env.install_gettext_translations(
68
            gettext.translation("notifylib-{}".format(self.plugin_name), localedir='/usr/share/locale', languages=[lang], fallback=True)
69 70
        )

71
    def render(self, data, media_type, lang):
72
        """Render using jinja in given language"""
73
        self._set_jinja_translation(lang)
74
        output = self.jinja_message_template.render(media=media_type, **data)
75 76

        return output