Switching over to a copy-paste version of python-telepathy's channel manager
[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                 h = self.handle(handleType, handleId) if handleId != 0 else None
180                 props = self._generate_props(type, h, suppressHandler)
181                 if hasattr(self, "_validate_handle"):
182                         # On newer python-telepathy
183                         self._validate_handle(props)
184
185                 chan = self._channelManager.channel_for_props(props, signal=True)
186                 path = chan._object_path
187                 _moduleLogger.info("RequestChannel Object Path: %s" % path)
188                 return path
189
190         @gtk_toolbox.log_exception(_moduleLogger)
191         def RequestHandles(self, handleType, names, sender):
192                 """
193                 For org.freedesktop.telepathy.Connection
194                 Overiding telepathy.server.Connecton to allow custom handles
195                 """
196                 self.check_connected()
197                 self.check_handle_type(handleType)
198
199                 handles = []
200                 for name in names:
201                         requestedHandleName = name.encode('utf-8')
202                         if handleType == telepathy.HANDLE_TYPE_CONTACT:
203                                 _moduleLogger.info("RequestHandles Contact: %s" % requestedHandleName)
204                                 requestedContactId, requestedContactNumber = handle.ContactHandle.from_handle_name(
205                                         requestedHandleName
206                                 )
207                                 h = handle.create_handle(self, 'contact', requestedContactId, requestedContactNumber)
208                         elif handleType == telepathy.HANDLE_TYPE_LIST:
209                                 # Support only server side (immutable) lists
210                                 _moduleLogger.info("RequestHandles List: %s" % requestedHandleName)
211                                 h = handle.create_handle(self, 'list', requestedHandleName)
212                         else:
213                                 raise telepathy.errors.NotAvailable('Handle type unsupported %d' % handleType)
214                         handles.append(h.id)
215                         self.add_client_handle(h, sender)
216                 return handles
217
218         def _generate_props(self, channelType, handle, suppressHandler, initiatorHandle=None):
219                 targetHandle = 0 if handle is None else handle.get_id()
220                 targetHandleType = telepathy.HANDLE_TYPE_NONE if handle is None else handle.get_type()
221                 props = {
222                         telepathy.CHANNEL_INTERFACE + '.ChannelType': channelType,
223                         telepathy.CHANNEL_INTERFACE + '.TargetHandle': targetHandle,
224                         telepathy.CHANNEL_INTERFACE + '.TargetHandleType': targetHandleType,
225                         telepathy.CHANNEL_INTERFACE + '.Requested': suppressHandler
226                 }
227
228                 if initiatorHandle is not None:
229                         props[telepathy.CHANNEL_INTERFACE + '.InitiatorHandle'] = initiatorHandle.id
230
231                 return props
232
233         @gobject_utils.async
234         @gtk_toolbox.log_exception(_moduleLogger)
235         def _on_conversations_updated(self, conv, conversationIds):
236                 # @todo get conversations update running
237                 # @todo test conversatiuons
238                 _moduleLogger.info("Incoming messages from: %r" % (conversationIds, ))
239                 for contactId, phoneNumber in conversationIds:
240                         h = handle.create_handle(self, 'contact', contactId, phoneNumber)
241                         # Just let the TextChannel decide whether it should be reported to the user or not
242                         props = self._generate_props(telepathy.CHANNEL_TYPE_TEXT, h, False)
243                         channel = self._channelManager.channel_for_props(props, signal=True)