Switching to a fremantle specific profile file
[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                 'username' : '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['username'])
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['username'].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         def handle(self, handleType, handleId):
91                 self.check_handle(handleType, handleId)
92                 return self._handles[handleType, handleId]
93
94         @gtk_toolbox.log_exception(_moduleLogger)
95         def Connect(self):
96                 """
97                 For org.freedesktop.telepathy.Connection
98                 """
99                 _moduleLogger.info("Connecting...")
100                 self.StatusChanged(
101                         telepathy.CONNECTION_STATUS_CONNECTING,
102                         telepathy.CONNECTION_STATUS_REASON_REQUESTED
103                 )
104                 try:
105                         cookieFilePath = None
106                         self._session = gvoice.session.Session(cookieFilePath)
107
108                         self._callback = coroutines.func_sink(
109                                 coroutines.expand_positional(
110                                         self._on_conversations_updated
111                                 )
112                         )
113                         self.session.conversations.updateSignalHandler.register_sink(
114                                 self._callback
115                         )
116                         self.session.login(*self._credentials)
117                         self.session.backend.set_callback_number(self._callbackNumber)
118                 except gvoice.backend.NetworkError, e:
119                         _moduleLogger.exception("Connection Failed")
120                         self.StatusChanged(
121                                 telepathy.CONNECTION_STATUS_DISCONNECTED,
122                                 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
123                         )
124                 except Exception, e:
125                         _moduleLogger.exception("Connection Failed")
126                         self.StatusChanged(
127                                 telepathy.CONNECTION_STATUS_DISCONNECTED,
128                                 telepathy.CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED
129                         )
130                 else:
131                         _moduleLogger.info("Connected")
132                         self.StatusChanged(
133                                 telepathy.CONNECTION_STATUS_CONNECTED,
134                                 telepathy.CONNECTION_STATUS_REASON_REQUESTED
135                         )
136
137         @gtk_toolbox.log_exception(_moduleLogger)
138         def Disconnect(self):
139                 """
140                 For org.freedesktop.telepathy.Connection
141                 @bug Not properly logging out.  Cookie files need to be per connection and removed
142                 """
143                 _moduleLogger.info("Disconnecting")
144                 try:
145                         self.session.conversations.updateSignalHandler.unregister_sink(
146                                 self._callback
147                         )
148                         self._callback = None
149                         self._channelManager.close()
150                         self.session.logout()
151                         self.session.close()
152                         self._session = None
153                         _moduleLogger.info("Disconnected")
154                 except Exception:
155                         _moduleLogger.exception("Disconnecting Failed")
156                 self.StatusChanged(
157                         telepathy.CONNECTION_STATUS_DISCONNECTED,
158                         telepathy.CONNECTION_STATUS_REASON_REQUESTED
159                 )
160                 self.manager.disconnected(self)
161
162         @gtk_toolbox.log_exception(_moduleLogger)
163         def RequestChannel(self, type, handleType, handleId, suppressHandler):
164                 """
165                 For org.freedesktop.telepathy.Connection
166
167                 @param type DBus interface name for base channel type
168                 @param handleId represents a contact, list, etc according to handleType
169
170                 @returns DBus object path for the channel created or retrieved
171                 """
172                 self.check_connected()
173                 self.check_handle(handleType, handleId)
174
175                 channel = None
176                 channelManager = self._channelManager
177                 handle = self.handle(handleType, handleId)
178
179                 if type == telepathy.CHANNEL_TYPE_CONTACT_LIST:
180                         _moduleLogger.info("RequestChannel ContactList")
181                         channel = channelManager.channel_for_list(handle, suppressHandler)
182                 elif type == telepathy.CHANNEL_TYPE_TEXT:
183                         _moduleLogger.info("RequestChannel Text")
184                         channel = channelManager.channel_for_text(handle, suppressHandler)
185                 elif type == telepathy.CHANNEL_TYPE_STREAMED_MEDIA:
186                         _moduleLogger.info("RequestChannel Media")
187                         channel = channelManager.channel_for_call(handle, suppressHandler)
188                 else:
189                         raise telepathy.errors.NotImplemented("unknown channel type %s" % type)
190
191                 _moduleLogger.info("RequestChannel Object Path: %s" % channel._object_path)
192                 return channel._object_path
193
194         @gtk_toolbox.log_exception(_moduleLogger)
195         def RequestHandles(self, handleType, names, sender):
196                 """
197                 For org.freedesktop.telepathy.Connection
198                 Overiding telepathy.server.Connecton to allow custom handles
199                 """
200                 self.check_connected()
201                 self.check_handle_type(handleType)
202
203                 handles = []
204                 for name in names:
205                         name = name.encode('utf-8')
206                         if handleType == telepathy.HANDLE_TYPE_CONTACT:
207                                 _moduleLogger.info("RequestHandles Contact: %s" % name)
208                                 h = self._create_contact_handle(name)
209                         elif handleType == telepathy.HANDLE_TYPE_LIST:
210                                 # Support only server side (immutable) lists
211                                 _moduleLogger.info("RequestHandles List: %s" % name)
212                                 h = handle.create_handle(self, 'list', name)
213                         else:
214                                 raise telepathy.errors.NotAvailable('Handle type unsupported %d' % handleType)
215                         handles.append(h.id)
216                         self.add_client_handle(h, sender)
217                 return handles
218
219         def _create_contact_handle(self, requestedHandleName):
220                 requestedContactId, requestedContactNumber = handle.ContactHandle.from_handle_name(
221                         requestedHandleName
222                 )
223                 h = handle.create_handle(self, 'contact', requestedContactId, requestedContactNumber)
224                 return h
225
226         @gobject_utils.async
227         @gtk_toolbox.log_exception(_moduleLogger)
228         def _on_conversations_updated(self, conv, conversationIds):
229                 # @todo get conversations update running
230                 # @todo test conversatiuons
231                 _moduleLogger.info("Incoming messages from: %r" % (conversationIds, ))
232                 channelManager = self._channelManager
233                 for contactId, phoneNumber in conversationIds:
234                         h = handle.create_handle(self, 'contact', contactId, phoneNumber)
235                         # Just let the TextChannel decide whether it should be reported to the user or not
236                         channel = channelManager.channel_for_text(h)