With manually tracking read/unread, I don't think I need this anymore
[theonering] / src / connection.py
1 import os
2 import weakref
3 import logging
4
5 import telepathy
6
7 import constants
8 import tp
9 import util.misc as misc_utils
10
11 import gvoice
12 import handle
13
14 import aliasing
15 import avatars
16 import capabilities
17 import contacts
18 import presence
19 import requests
20 import simple_presence
21
22 import autogv
23 import channel_manager
24
25
26 _moduleLogger = logging.getLogger(__name__)
27
28
29 class TheOneRingOptions(object):
30
31         ignoreDND = True
32
33         useGVContacts = True
34
35         assert gvoice.session.Session._DEFAULTS["contacts"][1] == "hours"
36         contactsPollPeriodInHours = gvoice.session.Session._DEFAULTS["contacts"][0]
37
38         assert gvoice.session.Session._DEFAULTS["voicemail"][1] == "minutes"
39         voicemailPollPeriodInMinutes = gvoice.session.Session._DEFAULTS["voicemail"][0]
40
41         assert gvoice.session.Session._DEFAULTS["texts"][1] == "minutes"
42         textsPollPeriodInMinutes = gvoice.session.Session._DEFAULTS["texts"][0]
43
44         def __init__(self, parameters = None):
45                 if parameters is None:
46                         return
47                 self.ignoreDND = parameters["ignore-dnd"]
48                 self.useGVContacts = parameters["use-gv-contacts"]
49                 self.contactsPollPeriodInHours = parameters['contacts-poll-period-in-hours']
50                 self.voicemailPollPeriodInMinutes = parameters['voicemail-poll-period-in-minutes']
51                 self.textsPollPeriodInMinutes = parameters['texts-poll-period-in-minutes']
52
53
54 class TheOneRingConnection(
55         tp.Connection,
56         aliasing.AliasingMixin,
57         avatars.AvatarsMixin,
58         capabilities.CapabilitiesMixin,
59         contacts.ContactsMixin,
60         requests.RequestsMixin,
61         simple_presence.TheOneRingPresence,
62         simple_presence.SimplePresenceMixin,
63         presence.PresenceMixin,
64 ):
65
66         # overiding base class variable
67         _mandatory_parameters = {
68                 'account': 's',
69                 'password': 's',
70         }
71         # overiding base class variable
72         _optional_parameters = {
73                 'forward': 's',
74                 'ignore-dnd': 'b',
75                 'use-gv-contacts': 'b',
76                 'contacts-poll-period-in-hours': 'i',
77                 'voicemail-poll-period-in-minutes': 'i',
78                 'texts-poll-period-in-minutes': 'i',
79         }
80         _parameter_defaults = {
81                 'forward': '',
82                 'ignore-dnd': TheOneRingOptions.ignoreDND,
83                 'use-gv-contacts': TheOneRingOptions.useGVContacts,
84                 'contacts-poll-period-in-hours': TheOneRingOptions.contactsPollPeriodInHours,
85                 'voicemail-poll-period-in-minutes': TheOneRingOptions.voicemailPollPeriodInMinutes,
86                 'texts-poll-period-in-minutes': TheOneRingOptions.textsPollPeriodInMinutes,
87         }
88         _secret_parameters = set((
89                 "password",
90         ))
91
92         @misc_utils.log_exception(_moduleLogger)
93         def __init__(self, manager, parameters):
94                 self._loggers = []
95
96                 self.check_parameters(parameters)
97                 account = unicode(parameters['account'])
98                 encodedAccount = parameters['account'].encode('utf-8')
99                 encodedPassword = parameters['password'].encode('utf-8')
100                 encodedCallback = misc_utils.normalize_number(parameters['forward'].encode('utf-8'))
101                 if encodedCallback and not misc_utils.is_valid_number(encodedCallback):
102                         raise telepathy.errors.InvalidArgument("Invalid forwarding number")
103
104                 # Connection init must come first
105                 self.__options = TheOneRingOptions(parameters)
106                 self.__session = gvoice.session.Session(
107                         cookiePath = os.path.join(constants._data_path_, "%s.cookies" % account),
108                         defaults = {
109                                 "contacts": (self.__options.contactsPollPeriodInHours, "hours"),
110                                 "voicemail": (self.__options.voicemailPollPeriodInMinutes, "minutes"),
111                                 "texts": (self.__options.textsPollPeriodInMinutes, "minutes"),
112                         },
113                 )
114                 tp.Connection.__init__(
115                         self,
116                         constants._telepathy_protocol_name_,
117                         account,
118                         constants._telepathy_implementation_name_
119                 )
120                 aliasing.AliasingMixin.__init__(self)
121                 avatars.AvatarsMixin.__init__(self)
122                 capabilities.CapabilitiesMixin.__init__(self)
123                 contacts.ContactsMixin.__init__(self)
124                 requests.RequestsMixin.__init__(self)
125                 simple_presence.TheOneRingPresence.__init__(self, self.__options.ignoreDND)
126                 simple_presence.SimplePresenceMixin.__init__(self, self)
127                 presence.PresenceMixin.__init__(self, self)
128
129                 self.__manager = weakref.proxy(manager)
130                 self.__credentials = (
131                         encodedAccount,
132                         encodedPassword,
133                 )
134                 self.__callbackNumberParameter = encodedCallback
135                 self.__channelManager = channel_manager.ChannelManager(self)
136
137                 self.__cachePath = os.sep.join((constants._data_path_, "cache", self.username))
138                 try:
139                         os.makedirs(self.__cachePath)
140                 except OSError, e:
141                         if e.errno != 17:
142                                 raise
143
144                 self.set_self_handle(handle.create_handle(self, 'connection'))
145                 self._plumbing = [
146                         autogv.NewGVConversations(weakref.ref(self)),
147                         autogv.RefreshVoicemail(weakref.ref(self)),
148                         autogv.AutoDisconnect(weakref.ref(self)),
149                         autogv.DelayEnableContactIntegration(constants._telepathy_implementation_name_),
150                 ]
151
152                 _moduleLogger.info("Connection to the account %s created" % account)
153                 self._timedDisconnect = autogv.TimedDisconnect(weakref.ref(self))
154                 self._timedDisconnect.start()
155
156         @property
157         def manager(self):
158                 return self.__manager
159
160         @property
161         def session(self):
162                 return self.__session
163
164         @property
165         def options(self):
166                 return self.__options
167
168         @property
169         def username(self):
170                 return self.__credentials[0]
171
172         @property
173         def callbackNumberParameter(self):
174                 return self.__callbackNumberParameter
175
176         def get_handle_by_name(self, handleType, handleName):
177                 requestedHandleName = handleName.encode('utf-8')
178
179                 # We need to return an existing or create a new handle.  Unfortunately
180                 # handle init's take care of normalizing the handle name.  So we have
181                 # to create a new handle regardless and burn some handle id's and burn
182                 # some extra memory of creating objects we throw away if the handle
183                 # already exists.
184                 if handleType == telepathy.HANDLE_TYPE_CONTACT:
185                         h = handle.create_handle(self, 'contact', requestedHandleName)
186                 elif handleType == telepathy.HANDLE_TYPE_LIST:
187                         # Support only server side (immutable) lists
188                         h = handle.create_handle(self, 'list', requestedHandleName)
189                 else:
190                         raise telepathy.errors.NotAvailable('Handle type unsupported %d' % handleType)
191
192                 for candidate in self._handles.itervalues():
193                         if candidate.get_name() == h.get_name():
194                                 h = candidate
195                                 _moduleLogger.debug("Re-used handle for %s, I hoped this helped" % handleName)
196                                 break
197
198                 return h
199
200         def log_to_user(self, component, message):
201                 for logger in self._loggers:
202                         logger.log_message(component, message)
203
204         def add_logger(self, logger):
205                 self._loggers.append(logger)
206
207         def remove_logger(self, logger):
208                 self._loggers.remove(logger)
209
210         @property
211         def _channel_manager(self):
212                 return self.__channelManager
213
214         @misc_utils.log_exception(_moduleLogger)
215         def Connect(self):
216                 """
217                 For org.freedesktop.telepathy.Connection
218                 """
219                 if self._status != telepathy.CONNECTION_STATUS_DISCONNECTED:
220                         _moduleLogger.info("Attempting connect when not disconnected")
221                         return
222                 _moduleLogger.info("Connecting...")
223                 self.StatusChanged(
224                         telepathy.CONNECTION_STATUS_CONNECTING,
225                         telepathy.CONNECTION_STATUS_REASON_REQUESTED
226                 )
227                 self._timedDisconnect.stop()
228                 self.session.login(
229                         self.__credentials[0],
230                         self.__credentials[1],
231                         self._on_login,
232                         self._on_login_error,
233                 )
234
235         @misc_utils.log_exception(_moduleLogger)
236         def _on_login(self, *args):
237                 _moduleLogger.info("Connected, setting up...")
238                 try:
239                         self.__session.load(self.__cachePath)
240
241                         for plumber in self._plumbing:
242                                 plumber.start()
243                         if not self.__callbackNumberParameter:
244                                 callback = gvoice.backend.get_sane_callback(
245                                         self.session.backend
246                                 )
247                                 self.__callbackNumberParameter = misc_utils.normalize_number(callback)
248                         self.session.backend.set_callback_number(self.__callbackNumberParameter)
249
250                         subscribeHandle = self.get_handle_by_name(telepathy.HANDLE_TYPE_LIST, "subscribe")
251                         subscribeProps = self.generate_props(telepathy.CHANNEL_TYPE_CONTACT_LIST, subscribeHandle, False)
252                         self.__channelManager.channel_for_props(subscribeProps, signal=True)
253                         publishHandle = self.get_handle_by_name(telepathy.HANDLE_TYPE_LIST, "publish")
254                         publishProps = self.generate_props(telepathy.CHANNEL_TYPE_CONTACT_LIST, publishHandle, False)
255                         self.__channelManager.channel_for_props(publishProps, signal=True)
256                 except Exception:
257                         _moduleLogger.exception("Setup failed")
258                         self.disconnect(telepathy.CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED)
259                         return
260
261                 _moduleLogger.info("Connected and set up")
262                 self.StatusChanged(
263                         telepathy.CONNECTION_STATUS_CONNECTED,
264                         telepathy.CONNECTION_STATUS_REASON_REQUESTED
265                 )
266
267         @misc_utils.log_exception(_moduleLogger)
268         def _on_login_error(self, error):
269                 _moduleLogger.error(error)
270                 if isinstance(error, StopIteration):
271                         pass
272                 elif isinstance(error, gvoice.backend.NetworkError):
273                         self.disconnect(telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR)
274                 else:
275                         self.disconnect(telepathy.CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED)
276
277         @misc_utils.log_exception(_moduleLogger)
278         def Disconnect(self):
279                 """
280                 For org.freedesktop.telepathy.Connection
281                 """
282                 _moduleLogger.info("Kicking off disconnect")
283                 self.disconnect(telepathy.CONNECTION_STATUS_REASON_REQUESTED)
284
285         @misc_utils.log_exception(_moduleLogger)
286         def RequestChannel(self, type, handleType, handleId, suppressHandler):
287                 """
288                 For org.freedesktop.telepathy.Connection
289
290                 @param type DBus interface name for base channel type
291                 @param handleId represents a contact, list, etc according to handleType
292
293                 @returns DBus object path for the channel created or retrieved
294                 """
295                 self.check_connected()
296                 self.check_handle(handleType, handleId)
297
298                 h = self.get_handle_by_id(handleType, handleId) if handleId != 0 else None
299                 props = self.generate_props(type, h, suppressHandler)
300                 self._validate_handle(props)
301
302                 chan = self.__channelManager.channel_for_props(props, signal=True)
303                 path = chan._object_path
304                 _moduleLogger.info("RequestChannel Object Path (%s): %s" % (type.rsplit(".", 1)[-1], path))
305                 return path
306
307         def generate_props(self, channelType, handleObj, suppressHandler, initiatorHandle=None):
308                 targetHandle = 0 if handleObj is None else handleObj.get_id()
309                 targetHandleType = telepathy.HANDLE_TYPE_NONE if handleObj is None else handleObj.get_type()
310                 props = {
311                         telepathy.CHANNEL_INTERFACE + '.ChannelType': channelType,
312                         telepathy.CHANNEL_INTERFACE + '.TargetHandle': targetHandle,
313                         telepathy.CHANNEL_INTERFACE + '.TargetHandleType': targetHandleType,
314                         telepathy.CHANNEL_INTERFACE + '.Requested': suppressHandler
315                 }
316
317                 if initiatorHandle is not None:
318                         props[telepathy.CHANNEL_INTERFACE + '.InitiatorHandle'] = initiatorHandle.id
319
320                 return props
321
322         def disconnect(self, reason):
323                 _moduleLogger.info("Disconnecting")
324
325                 self._timedDisconnect.stop()
326
327                 # Not having the disconnect first can cause weird behavior with clients
328                 # including not being able to reconnect or even crashing
329                 self.StatusChanged(
330                         telepathy.CONNECTION_STATUS_DISCONNECTED,
331                         reason,
332                 )
333
334                 for plumber in self._plumbing:
335                         plumber.stop()
336
337                 self.__channelManager.close()
338                 self.manager.disconnected(self)
339
340                 self.session.save(self.__cachePath)
341                 self.session.shutdown()
342                 self.session.close()
343
344                 # In case one of the above items takes too long (which it should never
345                 # do), we leave the starting of the shutdown-on-idle counter to the
346                 # very end
347                 self.manager.disconnect_completed()
348
349                 _moduleLogger.info("Disconnected")