Project

General

Profile

Statistics
| Branch: | Tag: | Revision:

vigiboard / vigiboard / controllers / plugins / date.py @ 24182db6

History | View | Annotate | Download (4.71 KB)

1
# -*- coding: utf-8 -*-
2
# vim:set expandtab tabstop=4 shiftwidth=4:
3
################################################################################
4
#
5
# Copyright (C) 2007-2015 CS-SI
6
#
7
# This program is free software; you can redistribute it and/or modify
8
# it under the terms of the GNU General Public License version 2 as
9
# published by the Free Software Foundation.
10
#
11
# This program is distributed in the hope that it will be useful,
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
# GNU General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License
17
# along with this program; if not, write to the Free Software
18
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
################################################################################
20

    
21
"""
22
Un plugin pour VigiBoard qui ajoute une colonne avec la date à laquelle
23
est survenu un événement et la durée depuis laquelle l'événement est actif.
24
"""
25
from datetime import datetime, timedelta
26
import tw.forms as twf
27
from pylons.i18n import ugettext as _, lazy_ugettext as l_
28

    
29
from vigilo.models import tables
30

    
31
from vigiboard.controllers.plugins import VigiboardRequestPlugin, ITEMS
32
from vigiboard.lib import dateformat
33

    
34

    
35
class ExampleDateFormat(object):
36
    """
37
    Une classe permettant d'obtenir un exemple de date
38
    correspondant au format de la locale de l'utilisateur.
39
    """
40
    def __str__(self):
41
        """
42
        Retourne l'heure courante au format attendu,
43
        encodée en UTF-8.
44

45
        @return: Heure courante au format attendu (en UTF-8).
46
        @rtype: C{str}
47
        """
48
        return unicode(self).encode('utf-8')
49

    
50
    def __unicode__(self):
51
        """
52
        Retourne l'heure courante au format attendu.
53

54
        @return: Heure courante au format attendu.
55
        @rtype: C{unicode}
56
        """
57
        format = dateformat.get_date_format()
58
        date = datetime.strftime(datetime.now(), format).decode('utf-8')
59
        return _('Eg. %(date)s') % {'date': date}
60

    
61

    
62
class PluginDate(VigiboardRequestPlugin):
63
    """Plugin pour l'ajout d'une colonne Date."""
64
    def get_search_fields(self):
65
        return [
66
            twf.Label('date', text=l_('Last occurrence')),
67
            twf.CalendarDateTimePicker(
68
                'from_date',
69
                label_text=l_('Between'),
70
                button_text=l_("Choose"),
71
                not_empty=False,
72
                validator=dateformat.DateFormatConverter(if_missing=None),
73
                date_format=dateformat.get_date_format,
74
                calendar_lang=dateformat.get_calendar_lang,
75
                attrs={
76
                    # Affiche un exemple de date au survol
77
                    # et en tant qu'indication (placeholder).
78
                    'title': ExampleDateFormat(),
79
                    'placeholder': ExampleDateFormat()
80
                },
81
            ),
82
            twf.CalendarDateTimePicker(
83
                'to_date',
84
                label_text=l_('And'),
85
                button_text=l_("Choose"),
86
                not_empty=False,
87
                validator=dateformat.DateFormatConverter(if_missing=None),
88
                date_format=dateformat.get_date_format,
89
                calendar_lang=dateformat.get_calendar_lang,
90
                attrs={
91
                    # Affiche un exemple de date au survol
92
                    # et en tant qu'indication (placeholder).
93
                    'title': ExampleDateFormat(),
94
                    'placeholder': ExampleDateFormat()
95
                },
96
            ),
97
        ]
98

    
99
    def handle_search_fields(self, query, search, state, subqueries):
100
        if state != ITEMS:
101
            return
102

    
103
        if search.get('from_date'):
104
            query.add_filter(tables.CorrEvent.timestamp_active >=
105
                search['from_date'])
106
        if search.get('to_date'):
107
            query.add_filter(tables.CorrEvent.timestamp_active <=
108
                search['to_date'])
109

    
110
    def get_data(self, event):
111
        state = tables.StateName.value_to_statename(
112
                    event[0].cause.current_state)
113
        # La résolution maximale de Nagios est la seconde.
114
        # On supprime les microsecondes qui ne nous apportent
115
        # aucune information et fausse l'affichage dans l'export CSV
116
        # en créant un nouvel objet timedelta dérivé du premier.
117
        duration = datetime.now() - event[0].timestamp_active
118
        duration = timedelta(days=duration.days, seconds=duration.seconds)
119
        return {
120
            'state': state,
121
            'date': event[0].cause.timestamp,
122
            'duration': duration,
123
        }
124

    
125
    def get_sort_criterion(self, query, column):
126
        if column == 'date':
127
            return tables.Event.timestamp
128
        return None
129