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