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