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