A bunch of todos
[theonering] / src / connection.py
1
2 """
3 @todo Add params for disable/enable state machines
4 @todo Separate voicemail/sms into separate conversation instances
5 @todo Setup addressbook, voicemail, sms state machines
6 @todo Add option to use screen name as callback
7 @todo Get a callback for missed calls to force an update of the voicemail state machine
8 @todo Get a callback on an incoming call and if its from GV, auto-pickup
9 @todo Use state-strategies to keep mega-state-machine generic
10 @todo Observe when connected/disconnected to disconnect CM
11 """
12
13
14 import weakref
15 import logging
16
17 import telepathy
18
19 import constants
20 import util.go_utils as gobject_utils
21 import util.coroutines as coroutines
22 import gtk_toolbox
23
24 import gvoice
25 import handle
26
27 import contacts
28 import aliasing
29 import simple_presence
30 import presence
31 import capabilities
32
33 import channel_manager
34
35
36 _moduleLogger = logging.getLogger("connection")
37
38
39 class TheOneRingConnection(
40         telepathy.server.Connection,
41         telepathy.server.ConnectionInterfaceRequests, # already a mixin
42         contacts.ContactsMixin,
43         aliasing.AliasingMixin,
44         simple_presence.SimplePresenceMixin,
45         presence.PresenceMixin,
46         capabilities.CapabilitiesMixin,
47 ):
48
49         # Overriding a base class variable
50         # Should the forwarding number be handled by the alias or by an option?
51         _mandatory_parameters = {
52                 'account' : 's',
53                 'password' : 's',
54                 'forward' : 's',
55         }
56         # Overriding a base class variable
57         _optional_parameters = {
58         }
59         _parameter_defaults = {
60         }
61
62         @gtk_toolbox.log_exception(_moduleLogger)
63         def __init__(self, manager, parameters):
64                 self.check_parameters(parameters)
65                 account = unicode(parameters['account'])
66                 encodedAccount = parameters['account'].encode('utf-8')
67                 encodedPassword = parameters['password'].encode('utf-8')
68                 encodedCallback = parameters['forward'].encode('utf-8')
69                 if not encodedCallback:
70                         raise telepathy.errors.InvalidArgument("User must specify what number GV forwards calls to")
71
72                 # Connection init must come first
73                 telepathy.server.Connection.__init__(
74                         self,
75                         constants._telepathy_protocol_name_,
76                         account,
77                         constants._telepathy_implementation_name_
78                 )
79                 telepathy.server.ConnectionInterfaceRequests.__init__(self)
80                 contacts.ContactsMixin.__init__(self)
81                 aliasing.AliasingMixin.__init__(self)
82                 simple_presence.SimplePresenceMixin.__init__(self)
83                 presence.PresenceMixin.__init__(self)
84                 capabilities.CapabilitiesMixin.__init__(self)
85
86                 self._manager = weakref.proxy(manager)
87                 self._credentials = (
88                         encodedAccount,
89                         encodedPassword,
90                 )
91                 self._callbackNumber = encodedCallback
92                 self._channelManager = channel_manager.ChannelManager(self)
93
94                 self._session = gvoice.session.Session(None)
95
96                 self.set_self_handle(handle.create_handle(self, 'connection'))
97
98                 self._callback = None
99                 _moduleLogger.info("Connection to the account %s created" % account)
100
101         @property
102         def manager(self):
103                 return self._manager
104
105         @property
106         def session(self):
107                 return self._session
108
109         @property
110         def username(self):
111                 return self._credentials[0]
112
113         @property
114         def userAliasType(self):
115                 return self.USER_ALIAS_ACCOUNT
116
117         def handle(self, handleType, handleId):
118                 self.check_handle(handleType, handleId)
119                 return self._handles[handleType, handleId]
120
121         @gtk_toolbox.log_exception(_moduleLogger)
122         def Connect(self):
123                 """
124                 For org.freedesktop.telepathy.Connection
125                 """
126                 _moduleLogger.info("Connecting...")
127                 self.StatusChanged(
128                         telepathy.CONNECTION_STATUS_CONNECTING,
129                         telepathy.CONNECTION_STATUS_REASON_REQUESTED
130                 )
131                 try:
132                         cookieFilePath = None
133                         self._session = gvoice.session.Session(cookieFilePath)
134
135                         self._callback = coroutines.func_sink(
136                                 coroutines.expand_positional(
137                                         self._on_conversations_updated
138                                 )
139                         )
140                         self.session.conversations.updateSignalHandler.register_sink(
141                                 self._callback
142                         )
143                         self.session.login(*self._credentials)
144                         self.session.backend.set_callback_number(self._callbackNumber)
145                 except gvoice.backend.NetworkError, e:
146                         _moduleLogger.exception("Connection Failed")
147                         self.StatusChanged(
148                                 telepathy.CONNECTION_STATUS_DISCONNECTED,
149                                 telepathy.CONNECTION_STATUS_REASON_NETWORK_ERROR
150                         )
151                 except Exception, e:
152                         _moduleLogger.exception("Connection Failed")
153                         self.StatusChanged(
154                                 telepathy.CONNECTION_STATUS_DISCONNECTED,
155                                 telepathy.CONNECTION_STATUS_REASON_AUTHENTICATION_FAILED
156                         )
157                 else:
158                         _moduleLogger.info("Connected")
159                         self.StatusChanged(
160                                 telepathy.CONNECTION_STATUS_CONNECTED,
161                                 telepathy.CONNECTION_STATUS_REASON_REQUESTED
162                         )
163
164         @gtk_toolbox.log_exception(_moduleLogger)
165         def Disconnect(self):
166                 """
167                 For org.freedesktop.telepathy.Connection
168                 @bug Not properly logging out.  Cookie files need to be per connection and removed
169                 """
170                 _moduleLogger.info("Disconnecting")
171                 try:
172                         self.session.conversations.updateSignalHandler.unregister_sink(
173                                 self._callback
174                         )
175                         self._callback = None
176                         self._channelManager.close()
177                         self.session.logout()
178                         self.session.close()
179                         self._session = None
180                         _moduleLogger.info("Disconnected")
181                 except Exception:
182                         _moduleLogger.exception("Disconnecting Failed")
183                 self.StatusChanged(
184                         telepathy.CONNECTION_STATUS_DISCONNECTED,
185                         telepathy.CONNECTION_STATUS_REASON_REQUESTED
186                 )
187                 self.manager.disconnected(self)
188
189         @gtk_toolbox.log_exception(_moduleLogger)
190         def RequestChannel(self, type, handleType, handleId, suppressHandler):
191                 """
192                 For org.freedesktop.telepathy.Connection
193
194                 @param type DBus interface name for base channel type
195                 @param handleId represents a contact, list, etc according to handleType
196
197                 @returns DBus object path for the channel created or retrieved
198                 """
199                 self.check_connected()
200                 self.check_handle(handleType, handleId)
201
202                 h = self.handle(handleType, handleId) if handleId != 0 else None
203                 props = self._generate_props(type, h, suppressHandler)
204                 if hasattr(self, "_validate_handle"):
205                         # HACK Newer python-telepathy
206                         self._validate_handle(props)
207
208                 chan = self._channelManager.channel_for_props(props, signal=True)
209                 path = chan._object_path
210                 _moduleLogger.info("RequestChannel Object Path: %s" % path)
211                 return path
212
213         @gtk_toolbox.log_exception(_moduleLogger)
214         def RequestHandles(self, handleType, names, sender):
215                 """
216                 For org.freedesktop.telepathy.Connection
217                 Overiding telepathy.server.Connecton to allow custom handles
218                 """
219                 self.check_connected()
220                 self.check_handle_type(handleType)
221
222                 handles = []
223                 for name in names:
224                         requestedHandleName = name.encode('utf-8')
225                         if handleType == telepathy.HANDLE_TYPE_CONTACT:
226                                 _moduleLogger.info("RequestHandles Contact: %s" % requestedHandleName)
227                                 requestedContactId, requestedContactNumber = handle.ContactHandle.from_handle_name(
228                                         requestedHandleName
229                                 )
230                                 h = handle.create_handle(self, 'contact', requestedContactId, requestedContactNumber)
231                         elif handleType == telepathy.HANDLE_TYPE_LIST:
232                                 # Support only server side (immutable) lists
233                                 _moduleLogger.info("RequestHandles List: %s" % requestedHandleName)
234                                 h = handle.create_handle(self, 'list', requestedHandleName)
235                         else:
236                                 raise telepathy.errors.NotAvailable('Handle type unsupported %d' % handleType)
237                         handles.append(h.id)
238                         self.add_client_handle(h, sender)
239                 return handles
240
241         def _generate_props(self, channelType, handle, suppressHandler, initiatorHandle=None):
242                 targetHandle = 0 if handle is None else handle.get_id()
243                 targetHandleType = telepathy.HANDLE_TYPE_NONE if handle is None else handle.get_type()
244                 props = {
245                         telepathy.CHANNEL_INTERFACE + '.ChannelType': channelType,
246                         telepathy.CHANNEL_INTERFACE + '.TargetHandle': targetHandle,
247                         telepathy.CHANNEL_INTERFACE + '.TargetHandleType': targetHandleType,
248                         telepathy.CHANNEL_INTERFACE + '.Requested': suppressHandler
249                 }
250
251                 if initiatorHandle is not None:
252                         props[telepathy.CHANNEL_INTERFACE + '.InitiatorHandle'] = initiatorHandle.id
253
254                 return props
255
256         @gobject_utils.async
257         @gtk_toolbox.log_exception(_moduleLogger)
258         def _on_conversations_updated(self, conv, conversationIds):
259                 # @todo get conversations update running
260                 # @todo test conversatiuons
261                 _moduleLogger.info("Incoming messages from: %r" % (conversationIds, ))
262                 for contactId, phoneNumber in conversationIds:
263                         h = handle.create_handle(self, 'contact', contactId, phoneNumber)
264                         # Just let the TextChannel decide whether it should be reported to the user or not
265                         props = self._generate_props(telepathy.CHANNEL_TYPE_TEXT, h, False)
266                         channel = self._channelManager.channel_for_props(props, signal=True)