Delaying import of backend to improve startup time by 100ms
[theonering] / src / autogv.py
1 import logging
2
3 import dbus
4 import telepathy
5
6 try:
7         import conic as _conic
8         conic = _conic
9 except (ImportError, OSError):
10         conic = None
11
12 try:
13         import osso as _osso
14         osso = _osso
15 except (ImportError, OSError):
16         osso = None
17
18 import constants
19 import util.coroutines as coroutines
20 import util.go_utils as gobject_utils
21 import util.tp_utils as telepathy_utils
22 import util.misc as misc_utils
23 import gvoice
24
25
26 _moduleLogger = logging.getLogger(__name__)
27
28
29 class NewGVConversations(object):
30
31         def __init__(self, connRef):
32                 self._connRef = connRef
33                 self.__callback = None
34
35         def start(self):
36                 self.__callback = coroutines.func_sink(
37                         coroutines.expand_positional(
38                                 self._on_conversations_updated
39                         )
40                 )
41                 self._connRef().session.voicemails.updateSignalHandler.register_sink(
42                         self.__callback
43                 )
44                 self._connRef().session.texts.updateSignalHandler.register_sink(
45                         self.__callback
46                 )
47
48         def stop(self):
49                 if self.__callback is None:
50                         _moduleLogger.info("New conversation monitor stopped without starting")
51                         return
52                 self._connRef().session.voicemails.updateSignalHandler.unregister_sink(
53                         self.__callback
54                 )
55                 self._connRef().session.texts.updateSignalHandler.unregister_sink(
56                         self.__callback
57                 )
58                 self.__callback = None
59
60         @misc_utils.log_exception(_moduleLogger)
61         def _on_conversations_updated(self, conv, conversationIds):
62                 _moduleLogger.debug("Incoming messages from: %r" % (conversationIds, ))
63                 for phoneNumber in conversationIds:
64                         h = self._connRef().get_handle_by_name(telepathy.HANDLE_TYPE_CONTACT, phoneNumber)
65                         # Just let the TextChannel decide whether it should be reported to the user or not
66                         props = self._connRef().generate_props(telepathy.CHANNEL_TYPE_TEXT, h, False)
67                         if self._connRef()._channel_manager.channel_exists(props):
68                                 _moduleLogger.debug("Chat box already open for texting conversation with %s" % phoneNumber)
69                                 continue
70
71                         # Maemo 4.1's RTComm opens a window for a chat regardless if a
72                         # message is received or not, so we need to do some filtering here
73                         mergedConv = conv.get_conversation(phoneNumber)
74                         newConversations = mergedConv.conversations
75                         newConversations = gvoice.conversations.filter_out_read(newConversations)
76                         newConversations = gvoice.conversations.filter_out_self(newConversations)
77                         newConversations = list(newConversations)
78                         if not newConversations:
79                                 _moduleLogger.debug("Not opening chat box for %s, all new messages are either read or from yourself" % phoneNumber)
80                                 continue
81
82                         chan = self._connRef()._channel_manager.channel_for_props(props, signal=True)
83
84
85 class RefreshVoicemail(object):
86
87         def __init__(self, connRef):
88                 self._connRef = connRef
89                 self._newChannelSignaller = telepathy_utils.NewChannelSignaller(self._on_new_channel)
90                 self._outstandingRequests = []
91                 self._isStarted = False
92
93         def start(self):
94                 self._newChannelSignaller.start()
95                 self._isStarted = True
96
97         def stop(self):
98                 if not self._isStarted:
99                         _moduleLogger.info("voicemail monitor stopped without starting")
100                         return
101                 _moduleLogger.info("Stopping voicemail refresh")
102                 self._newChannelSignaller.stop()
103
104                 # I don't want to trust whether the cancel happens within the current
105                 # callback or not which could be the deciding factor between invalid
106                 # iterators or infinite loops
107                 localRequests = [r for r in self._outstandingRequests]
108                 for request in localRequests:
109                         localRequests.cancel()
110
111                 self._isStarted = False
112
113         @misc_utils.log_exception(_moduleLogger)
114         def _on_new_channel(self, bus, serviceName, connObjectPath, channelObjectPath, channelType):
115                 if channelType != telepathy.interfaces.CHANNEL_TYPE_STREAMED_MEDIA:
116                         return
117
118                 cmName = telepathy_utils.cm_from_path(connObjectPath)
119                 if cmName == constants._telepathy_implementation_name_:
120                         _moduleLogger.debug("Ignoring channels from self to prevent deadlock")
121                         return
122
123                 conn = telepathy.client.Connection(serviceName, connObjectPath)
124                 try:
125                         chan = telepathy.client.Channel(serviceName, channelObjectPath)
126                 except dbus.exceptions.UnknownMethodException:
127                         _moduleLogger.exception("Client might not have implemented a deprecated method")
128                         return
129                 missDetection = telepathy_utils.WasMissedCall(
130                         bus, conn, chan, self._on_missed_call, self._on_error_for_missed
131                 )
132                 self._outstandingRequests.append(missDetection)
133
134         @misc_utils.log_exception(_moduleLogger)
135         def _on_missed_call(self, missDetection):
136                 _moduleLogger.info("Missed a call")
137                 self._connRef().session.voicemailsStateMachine.reset_timers()
138                 self._outstandingRequests.remove(missDetection)
139
140         @misc_utils.log_exception(_moduleLogger)
141         def _on_error_for_missed(self, missDetection, reason):
142                 _moduleLogger.debug("Error: %r claims %r" % (missDetection, reason))
143                 self._outstandingRequests.remove(missDetection)
144
145
146 class TimedDisconnect(object):
147
148         def __init__(self, connRef):
149                 self._connRef = connRef
150                 self.__delayedDisconnect = gobject_utils.Timeout(self._on_delayed_disconnect)
151
152         def start(self):
153                 self.__delayedDisconnect.start(seconds=60)
154
155         def stop(self):
156                 self.__delayedDisconnect.cancel()
157
158         @misc_utils.log_exception(_moduleLogger)
159         def _on_delayed_disconnect(self):
160                 _moduleLogger.info("Timed disconnect occurred")
161                 self._connRef().disconnect(telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR)
162
163
164 class AutoDisconnect(object):
165
166         def __init__(self, connRef):
167                 self._connRef = connRef
168                 if conic is not None:
169                         self.__connection = conic.Connection()
170                 else:
171                         self.__connection = None
172
173                 self.__connectionEventId = None
174                 self.__delayedDisconnect = gobject_utils.Timeout(self._on_delayed_disconnect)
175
176         def start(self):
177                 if self.__connection is not None:
178                         self.__connectionEventId = self.__connection.connect("connection-event", self._on_connection_change)
179
180         def stop(self):
181                 self._cancel_delayed_disconnect()
182
183         @misc_utils.log_exception(_moduleLogger)
184         def _on_connection_change(self, connection, event):
185                 """
186                 @note Maemo specific
187                 """
188                 status = event.get_status()
189                 error = event.get_error()
190                 iap_id = event.get_iap_id()
191                 bearer = event.get_bearer_type()
192
193                 if status == conic.STATUS_DISCONNECTED:
194                         _moduleLogger.info("Disconnected from network, starting countdown to logoff")
195                         self.__delayedDisconnect.start(seconds=5)
196                 elif status == conic.STATUS_CONNECTED:
197                         _moduleLogger.info("Connected to network")
198                         self._cancel_delayed_disconnect()
199                 else:
200                         _moduleLogger.info("Other status: %r" % (status, ))
201
202         @misc_utils.log_exception(_moduleLogger)
203         def _cancel_delayed_disconnect(self):
204                 _moduleLogger.info("Cancelling auto-log off")
205                 self.__delayedDisconnect.cancel()
206
207         @misc_utils.log_exception(_moduleLogger)
208         def _on_delayed_disconnect(self):
209                 if not self._connRef().session.is_logged_in():
210                         _moduleLogger.info("Received connection change event when not logged in")
211                         return
212                 try:
213                         self._connRef().disconnect(telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR)
214                 except Exception:
215                         _moduleLogger.exception("Error durring disconnect")
216
217
218 class DisconnectOnShutdown(object):
219         """
220         I'm unsure when I get notified of shutdown or if I have enough time to do
221         anything about it, but thought this might help
222         """
223
224         def __init__(self, connRef):
225                 self._connRef = connRef
226
227                 self._osso = None
228                 self._deviceState = None
229
230         def start(self):
231                 if osso is not None:
232                         self._osso = osso.Context(constants.__app_name__, constants.__version__, False)
233                         self._deviceState = osso.DeviceState(self._osso)
234                         self._deviceState.set_device_state_callback(self._on_device_state_change, 0)
235                 else:
236                         _moduleLogger.warning("No device state support")
237
238         def stop(self):
239                 try:
240                         self._deviceState.close()
241                 except AttributeError:
242                         pass # Either None or close was removed (in Fremantle)
243                 self._deviceState = None
244                 try:
245                         self._osso.close()
246                 except AttributeError:
247                         pass # Either None or close was removed (in Fremantle)
248                 self._osso = None
249
250         @misc_utils.log_exception(_moduleLogger)
251         def _on_device_state_change(self, shutdown, save_unsaved_data, memory_low, system_inactivity, message, userData):
252                 """
253                 @note Hildon specific
254                 """
255                 try:
256                         self._connRef().disconnect(telepathy.CONNECTION_STATUS_REASON_REQUESTED)
257                 except Exception:
258                         _moduleLogger.exception("Error durring disconnect")
259
260
261 class DelayEnableContactIntegration(object):
262
263         def __init__(self, protocolName):
264                 self.__enableSystemContactSupport = telepathy_utils.EnableSystemContactIntegration(
265                         protocolName
266                 )
267                 self.__delayedEnable = gobject_utils.Async(self._on_delayed_enable)
268
269         def start(self):
270                 self.__delayedEnable.start()
271
272         def stop(self):
273                 self.__delayedEnable.cancel()
274
275         @misc_utils.log_exception(_moduleLogger)
276         def _on_delayed_enable(self):
277                 try:
278                         self.__enableSystemContactSupport.start()
279                 except dbus.DBusException, e:
280                         _moduleLogger.info("Contact integration seems to not be supported (%s)" % e)