1# This file is part of Gajim.
2#
3# Gajim is free software; you can redistribute it and/or modify
4# it under the terms of the GNU General Public License as published
5# by the Free Software Foundation; version 3 only.
6#
7# Gajim is distributed in the hope that it will be useful,
8# but WITHOUT ANY WARRANTY; without even the implied warranty of
9# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10# GNU General Public License for more details.
11#
12# You should have received a copy of the GNU General Public License
13# along with Gajim.  If not, see <http://www.gnu.org/licenses/>.
14
15# XEP-0202: Entity Time
16
17import time
18
19import nbxmpp
20from nbxmpp.namespaces import Namespace
21from nbxmpp.structs import StanzaHandler
22from nbxmpp.modules.date_and_time import parse_datetime
23from nbxmpp.modules.date_and_time import create_tzinfo
24
25from gajim.common import app
26from gajim.common.nec import NetworkEvent
27from gajim.common.modules.base import BaseModule
28
29
30class EntityTime(BaseModule):
31    def __init__(self, con):
32        BaseModule.__init__(self, con)
33
34        self.handlers = [
35            StanzaHandler(name='iq',
36                          callback=self._answer_request,
37                          typ='get',
38                          ns=Namespace.TIME_REVISED),
39        ]
40
41    def request_entity_time(self, jid, resource):
42        if not app.account_is_available(self._account):
43            return
44
45        if resource:
46            jid += '/' + resource
47        iq = nbxmpp.Iq(to=jid, typ='get')
48        iq.addChild('time', namespace=Namespace.TIME_REVISED)
49
50        self._log.info('Requested: %s', jid)
51
52        self._con.connection.SendAndCallForResponse(iq, self._result_received)
53
54    def _result_received(self, _nbxmpp_client, stanza):
55        time_info = None
56        if not nbxmpp.isResultNode(stanza):
57            self._log.info('Error: %s', stanza.getError())
58        else:
59            time_info = self._extract_info(stanza)
60
61        self._log.info('Received: %s %s', stanza.getFrom(), time_info)
62
63        app.nec.push_incoming_event(NetworkEvent('time-result-received',
64                                                 conn=self._con,
65                                                 jid=stanza.getFrom(),
66                                                 time_info=time_info))
67
68    def _extract_info(self, stanza):
69        time_ = stanza.getTag('time')
70        if not time_:
71            self._log.warning('No time node: %s', stanza)
72            return None
73
74        tzo = time_.getTag('tzo').getData()
75        if not tzo:
76            self._log.warning('Wrong tzo node: %s', stanza)
77            return None
78
79        remote_tz = create_tzinfo(tz_string=tzo)
80        if remote_tz is None:
81            self._log.warning('Wrong tzo node: %s', stanza)
82            return None
83
84        utc_time = time_.getTag('utc').getData()
85        date_time = parse_datetime(utc_time, check_utc=True)
86        if date_time is None:
87            self._log.warning('Wrong timezone definition: %s %s',
88                              utc_time, stanza.getFrom())
89            return None
90
91        date_time = date_time.astimezone(remote_tz)
92        return date_time.strftime('%c %Z')
93
94    def _answer_request(self, _con, stanza, _properties):
95        self._log.info('%s asked for the time', stanza.getFrom())
96        if app.settings.get_account_setting(self._account, 'send_time_info'):
97            iq = stanza.buildReply('result')
98            time_ = iq.setTag('time', namespace=Namespace.TIME_REVISED)
99            formated_time = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
100            time_.setTagData('utc', formated_time)
101            isdst = time.localtime().tm_isdst
102            zone = -(time.timezone, time.altzone)[isdst] / 60.0
103            tzo = (zone / 60, abs(zone % 60))
104            time_.setTagData('tzo', '%+03d:%02d' % (tzo))
105            self._log.info('Answer: %s %s', formated_time, '%+03d:%02d' % (tzo))
106        else:
107            iq = stanza.buildReply('error')
108            err = nbxmpp.ErrorNode(nbxmpp.ERR_SERVICE_UNAVAILABLE)
109            iq.addChild(node=err)
110            self._log.info('Send service-unavailable')
111        self._con.connection.send(iq)
112        raise nbxmpp.NodeProcessed
113
114
115def get_instance(*args, **kwargs):
116    return EntityTime(*args, **kwargs), 'EntityTime'
117