Some todos
[theonering] / src / connection.py
1
2 """
3 @todo Add params for disable/enable state machines
4 @todo Separate voicemail/sms into separate conversation instances
5 @todo Setup addressbook, voicemail, sms state machines
6 @todo Add option to use screen name as callback
7 """
8
9
10 import weakref
11 import logging
12
13 import telepathy
14
15 import constants
16 import util.go_utils as gobject_utils
17 import util.coroutines as coroutines
18 import gtk_toolbox
19 import gvoice
20 import handle
21 import aliasing
22 import simple_presence
23 import presence
24 import capabilities
25 import channel_manager
26
27
28 _moduleLogger = logging.getLogger("connection")
29
30
31 class TheOneRingConnection(
32         telepathy.server.Connection,
33         aliasing.AliasingMixin,
34         simple_presence.SimplePresenceMixin,
35         presence.PresenceMixin,
36         capabilities.CapabilitiesMixin,
37 ):
38
39         # Overriding a base class variable
40         # Should the forwarding number be handled by the alias or by an option?
41         _mandatory_parameters = {
42                 'account' : 's',
43                 'password' : 's',
44                 'forward' : 's',
45         }
46         # Overriding a base class variable
47         _optional_parameters = {
48         }
49         _parameter_defaults = {
50         }
51
52         def __init__(self, manager, parameters):
53                 self.check_parameters(parameters)
54                 try:
55                         account = unicode(parameters['account'])
56
57                         # Connection init must come first
58                         telepathy.server.Connection.__init__(
59                                 self,
60                                 constants._telepathy_protocol_name_,
61                                 account,
62                                 constants._telepathy_implementation_name_
63                         )
64                         aliasing.AliasingMixin.__init__(self)
65                         simple_presence.SimplePresenceMixin.__init__(self)
66                         presence.PresenceMixin.__init__(self)
67                         capabilities.CapabilitiesMixin.__init__(self)
68
69                         self._manager = weakref.proxy(manager)
70                         self._credentials = (
71                                 parameters['account'].encode('utf-8'),
72                                 parameters['password'].encode('utf-8'),
73                         )
74                         self._callbackNumber = parameters['forward'].encode('utf-8')
75                         self._channelManager = channel_manager.ChannelManager(self)
76
77                         self._session = gvoice.session.Session(None)
78
79                         self.set_self_handle(handle.create_handle(self, 'connection'))
80
81                         self._callback = None
82                         _moduleLogger.info("Connection to the account %s created" % account)
83                 except Exception, e:
84                         _moduleLogger.exception("Failed to create Connection")
85                         raise
86
87         @property
88         def manager(self):
89                 return self._manager
90
91         @property
92         def session(self):
93                 return self._session
94
95         @property
96         def username(self):
97                 return self._credentials[0]
98
99         @property
100         def userAliasType(self):
101                 return self.USER_ALIAS_ACCOUNT
102
103         def handle(self, handleType, handleId):
104                 self.check_handle(handleType, handleId)
105                 return self._handles[handleType, handleId]
106
107         @gtk_toolbox.log_exception(_moduleLogger)
108         def Connect(self):
109                 """
110                 For org.freedesktop.telepathy.Connection
111                 """
112                 _moduleLogger.info("Connecting...")
113                 self.StatusChanged(
114                         telepathy.CONNECTION_STATUS_CONNECTING,
115                         telepathy.CONNECTION_STATUS_REASON_REQUESTED
116                 )
117                 try:
118                         cookieFilePath = None
119                         self._session = gvoice.session.Session(cookieFilePath)
120
121                         self._callback = coroutines.func_sink(
122                                 coroutines.expand_positional(
123                                         self._on_conversations_updated
124                                 )
125                         )
126                         self.session.conversations.updateSignalHandler.register_sink(
127                                 self._callback
128                         )
129                         self.session.login(*self._credentials)
130                         self.session.backend.set_callback_number(self._callbackNumber)
131                 except gvoice.backend.NetworkError, e:
132                         _moduleLogger.exception("Connection Failed")
133                         self.StatusChanged(
134                                 telepathy.CONNECTION_STATUS_DISCONNECTED,
135                                 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
136                         )
137                 except Exception, e:
138                         _moduleLogger.exception("Connection Failed")
139                         self.StatusChanged(
140                                 telepathy.CONNECTION_STATUS_DISCONNECTED,
141                                 telepathy.CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED
142                         )
143                 else:
144                         _moduleLogger.info("Connected")
145                         self.StatusChanged(
146                                 telepathy.CONNECTION_STATUS_CONNECTED,
147                                 telepathy.CONNECTION_STATUS_REASON_REQUESTED
148                         )
149
150         @gtk_toolbox.log_exception(_moduleLogger)
151         def Disconnect(self):
152                 """
153                 For org.freedesktop.telepathy.Connection
154                 @bug Not properly logging out.  Cookie files need to be per connection and removed
155                 """
156                 _moduleLogger.info("Disconnecting")
157                 try:
158                         self.session.conversations.updateSignalHandler.unregister_sink(
159                                 self._callback
160                         )
161                         self._callback = None
162                         self._channelManager.close()
163                         self.session.logout()
164                         self.session.close()
165                         self._session = None
166                         _moduleLogger.info("Disconnected")
167                 except Exception:
168                         _moduleLogger.exception("Disconnecting Failed")
169                 self.StatusChanged(
170                         telepathy.CONNECTION_STATUS_DISCONNECTED,
171                         telepathy.CONNECTION_STATUS_REASON_REQUESTED
172                 )
173                 self.manager.disconnected(self)
174
175         @gtk_toolbox.log_exception(_moduleLogger)
176         def RequestChannel(self, type, handleType, handleId, suppressHandler):
177                 """
178                 For org.freedesktop.telepathy.Connection
179
180                 @param type DBus interface name for base channel type
181                 @param handleId represents a contact, list, etc according to handleType
182
183                 @returns DBus object path for the channel created or retrieved
184                 """
185                 self.check_connected()
186                 self.check_handle(handleType, handleId)
187
188                 h = self.handle(handleType, handleId) if handleId != 0 else None
189                 props = self._generate_props(type, h, suppressHandler)
190                 if hasattr(self, "_validate_handle"):
191                         # HACK Newer python-telepathy
192                         self._validate_handle(props)
193
194                 chan = self._channelManager.channel_for_props(props, signal=True)
195                 path = chan._object_path
196                 _moduleLogger.info("RequestChannel Object Path: %s" % path)
197                 return path
198
199         @gtk_toolbox.log_exception(_moduleLogger)
200         def RequestHandles(self, handleType, names, sender):
201                 """
202                 For org.freedesktop.telepathy.Connection
203                 Overiding telepathy.server.Connecton to allow custom handles
204                 """
205                 self.check_connected()
206                 self.check_handle_type(handleType)
207
208                 handles = []
209                 for name in names:
210                         requestedHandleName = name.encode('utf-8')
211                         if handleType == telepathy.HANDLE_TYPE_CONTACT:
212                                 _moduleLogger.info("RequestHandles Contact: %s" % requestedHandleName)
213                                 requestedContactId, requestedContactNumber = handle.ContactHandle.from_handle_name(
214                                         requestedHandleName
215                                 )
216                                 h = handle.create_handle(self, 'contact', requestedContactId, requestedContactNumber)
217                         elif handleType == telepathy.HANDLE_TYPE_LIST:
218                                 # Support only server side (immutable) lists
219                                 _moduleLogger.info("RequestHandles List: %s" % requestedHandleName)
220                                 h = handle.create_handle(self, 'list', requestedHandleName)
221                         else:
222                                 raise telepathy.errors.NotAvailable('Handle type unsupported %d' % handleType)
223                         handles.append(h.id)
224                         self.add_client_handle(h, sender)
225                 return handles
226
227         def _generate_props(self, channelType, handle, suppressHandler, initiatorHandle=None):
228                 targetHandle = 0 if handle is None else handle.get_id()
229                 targetHandleType = telepathy.HANDLE_TYPE_NONE if handle is None else handle.get_type()
230                 props = {
231                         telepathy.CHANNEL_INTERFACE + '.ChannelType': channelType,
232                         telepathy.CHANNEL_INTERFACE + '.TargetHandle': targetHandle,
233                         telepathy.CHANNEL_INTERFACE + '.TargetHandleType': targetHandleType,
234                         telepathy.CHANNEL_INTERFACE + '.Requested': suppressHandler
235                 }
236
237                 if initiatorHandle is not None:
238                         props[telepathy.CHANNEL_INTERFACE + '.InitiatorHandle'] = initiatorHandle.id
239
240                 return props
241
242         @gobject_utils.async
243         @gtk_toolbox.log_exception(_moduleLogger)
244         def _on_conversations_updated(self, conv, conversationIds):
245                 # @todo get conversations update running
246                 # @todo test conversatiuons
247                 _moduleLogger.info("Incoming messages from: %r" % (conversationIds, ))
248                 for contactId, phoneNumber in conversationIds:
249                         h = handle.create_handle(self, 'contact', contactId, phoneNumber)
250                         # Just let the TextChannel decide whether it should be reported to the user or not
251                         props = self._generate_props(telepathy.CHANNEL_TYPE_TEXT, h, False)
252                         channel = self._channelManager.channel_for_props(props, signal=True)