Project

General

Profile

Statistics
| Branch: | Tag: | Revision:

vigiboard / vigiboard / controllers / plugins / date.py @ 25892058

History | View | Annotate | Download (3.99 KB)

1
# -*- coding: utf-8 -*-
2
# vim:set expandtab tabstop=4 shiftwidth=4:
3
################################################################################
4
#
5
# Copyright (C) 2007-2013 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
from tg.i18n import get_lang
29
import tg
30
from babel import Locale
31

    
32
from vigilo.turbogears.helpers import get_locales
33
from vigilo.models import tables
34

    
35
from vigiboard.controllers.plugins import VigiboardRequestPlugin, ITEMS
36
from vigiboard.lib.dateformat import DateFormatConverter
37

    
38
def get_calendar_lang():
39
    # TODO: Utiliser le champ "language" du modèle pour cet utilisateur ?
40
    # On récupère la langue du navigateur de l'utilisateur
41
    lang = get_lang()
42
    if not lang:
43
        lang = tg.config['lang']
44
    else:
45
        lang = lang[0]
46

    
47
    # TODO: Il faudrait gérer les cas où tout nous intéresse dans "lang".
48
    # Si l'identifiant de langage est composé (ex: "fr_FR"),
49
    # on ne récupère que la 1ère partie.
50
    lang = lang.replace('_', '-')
51
    lang = lang.split('-')[0]
52
    return lang
53

    
54
def get_date_format():
55
    # @HACK: nécessaire car l_() retourne un object LazyString
56
    # qui n'est pas sérialisable en JSON.
57
    return _('%Y-%m-%d %I:%M:%S %p').encode('utf-8')
58

    
59
class PluginDate(VigiboardRequestPlugin):
60
    """Plugin pour l'ajout d'une colonne Date."""
61
    def get_search_fields(self):
62
        return [
63
            twf.CalendarDateTimePicker(
64
                'from_date',
65
                label_text=l_('From'),
66
                button_text=l_("Choose"),
67
                not_empty=False,
68
                validator=DateFormatConverter(if_missing=None),
69
                date_format=get_date_format,
70
                calendar_lang=get_calendar_lang,
71
            ),
72
            twf.CalendarDateTimePicker(
73
                'to_date',
74
                label_text=l_('To'),
75
                button_text=l_("Choose"),
76
                not_empty=False,
77
                validator=DateFormatConverter(if_missing=None),
78
                date_format=get_date_format,
79
                calendar_lang=get_calendar_lang,
80
            ),
81
        ]
82

    
83
    def handle_search_fields(self, query, search, state, subqueries):
84
        if state != ITEMS:
85
            return
86

    
87
        if search.get('from_date'):
88
            query.add_filter(tables.CorrEvent.timestamp_active >=
89
                search['from_date'])
90
        if search.get('to_date'):
91
            query.add_filter(tables.CorrEvent.timestamp_active <=
92
                search['to_date'])
93

    
94
    def get_data(self, event):
95
        state = tables.StateName.value_to_statename(
96
                    event[0].cause.current_state)
97
        # La résolution maximale de Nagios est la seconde.
98
        # On supprime les microsecondes qui ne nous apportent
99
        # aucune information et fausse l'affichage dans l'export CSV
100
        # en créant un nouvel objet timedelta dérivé du premier.
101
        duration = datetime.now() - event[0].timestamp_active
102
        duration = timedelta(days=duration.days, seconds=duration.seconds)
103
        return {
104
            'state': state,
105
            'date': event[0].cause.timestamp,
106
            'duration': duration,
107
        }