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