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