5fe94de51327b2712d1e5e672f7c8c738991c87e
[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                 try:
41                         self.check_parameters(parameters)
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                         _moduleLogger.info("Disconnected")
130                 except Exception:
131                         _moduleLogger.exception("Disconnecting Failed")
132                 self.StatusChanged(
133                         telepathy.CONNECTION_STATUS_DISCONNECTED,
134                         telepathy.CONNECTION_STATUS_REASON_REQUESTED
135                 )
136
137         @gtk_toolbox.log_exception(_moduleLogger)
138         def RequestChannel(self, type, handleType, handleId, suppressHandler):
139                 """
140                 For org.freedesktop.telepathy.Connection
141
142                 @param type DBus interface name for base channel type
143                 @param handleId represents a contact, list, etc according to handleType
144
145                 @returns DBus object path for the channel created or retrieved
146                 """
147                 self.check_connected()
148                 self.check_handle(handleType, handleId)
149
150                 channel = None
151                 channelManager = self._channelManager
152                 handle = self.handle(handleType, handleId)
153
154                 if type == telepathy.CHANNEL_TYPE_CONTACT_LIST:
155                         _moduleLogger.info("RequestChannel ContactList")
156                         channel = channelManager.channel_for_list(handle, suppressHandler)
157                 elif type == telepathy.CHANNEL_TYPE_TEXT:
158                         _moduleLogger.info("RequestChannel Text")
159                         channel = channelManager.channel_for_text(handle, suppressHandler)
160                 elif type == telepathy.CHANNEL_TYPE_STREAMED_MEDIA:
161                         _moduleLogger.info("RequestChannel Media")
162                         channel = channelManager.channel_for_call(handle, suppressHandler)
163                 else:
164                         raise telepathy.errors.NotImplemented("unknown channel type %s" % type)
165
166                 _moduleLogger.info("RequestChannel Object Path: %s" % channel._object_path)
167                 return channel._object_path
168
169         @gtk_toolbox.log_exception(_moduleLogger)
170         def RequestHandles(self, handleType, names, sender):
171                 """
172                 For org.freedesktop.telepathy.Connection
173                 Overiding telepathy.server.Connecton to allow custom handles
174                 """
175                 self.check_connected()
176                 self.check_handle_type(handleType)
177
178                 handles = []
179                 for name in names:
180                         name = name.encode('utf-8')
181                         if handleType == telepathy.HANDLE_TYPE_CONTACT:
182                                 _moduleLogger.info("RequestHandles Contact: %s" % name)
183                                 h = self._create_contact_handle(name)
184                         elif handleType == telepathy.HANDLE_TYPE_LIST:
185                                 # Support only server side (immutable) lists
186                                 _moduleLogger.info("RequestHandles List: %s" % name)
187                                 h = handle.create_handle(self, 'list', name)
188                         else:
189                                 raise telepathy.errors.NotAvailable('Handle type unsupported %d' % handleType)
190                         handles.append(h.id)
191                         self.add_client_handle(h, sender)
192                 return handles
193
194         def _create_contact_handle(self, requestedHandleName):
195                 requestedContactId, requestedContactNumber = handle.ContactHandle.from_handle_name(
196                         requestedHandleName
197                 )
198                 h = handle.create_handle(self, 'contact', requestedContactId, requestedContactNumber)
199                 return h
200
201         @coroutines.func_sink
202         @coroutines.expand_positional
203         @gobject_utils.async
204         def _on_conversations_updated(self, conversationIds):
205                 # @todo get conversations update running
206                 # @todo test conversatiuons
207                 channelManager = self._channelManager
208                 for contactId, phoneNumber in conversationIds:
209                         h = self._create_contact_handle(contactId, phoneNumber)
210                         # if its new, __init__ will take care of things
211                         # if its old, its own update will take care of it
212                         channel = channelManager.channel_for_text(handle)