11 from PyQt4 import QtCore
13 from util import qore_utils
14 from util import concurrent
15 from util import misc as misc_utils
20 _moduleLogger = logging.getLogger(__name__)
23 class _DraftContact(object):
25 def __init__(self, title, description, numbersWithDescriptions):
27 self.description = description
28 self.numbers = numbersWithDescriptions
29 self.selectedNumber = numbersWithDescriptions[0][0]
32 class Draft(QtCore.QObject):
34 sendingMessage = QtCore.pyqtSignal()
35 sentMessage = QtCore.pyqtSignal()
36 calling = QtCore.pyqtSignal()
37 called = QtCore.pyqtSignal()
38 cancelling = QtCore.pyqtSignal()
39 cancelled = QtCore.pyqtSignal()
40 error = QtCore.pyqtSignal(str)
42 recipientsChanged = QtCore.pyqtSignal()
44 def __init__(self, pool, backend):
45 QtCore.QObject.__init__(self)
48 self._backend = backend
51 assert 0 < len(self._contacts)
52 numbers = [contact.selectedNumber for contact in self._contacts.itervalues()]
53 le = concurrent.AsyncLinearExecution(self._pool, self._send)
54 le.start(numbers, text)
57 assert len(self._contacts) == 1
58 (contact, ) = self._contacts.itervalues()
59 le = concurrent.AsyncLinearExecution(self._pool, self._call)
60 le.start(contact.selectedNumber)
63 le = concurrent.AsyncLinearExecution(self._pool, self._cancel)
66 def add_contact(self, contactId, title, description, numbersWithDescriptions):
67 assert contactId not in self._contacts
68 contactDetails = _DraftContact(title, description, numbersWithDescriptions)
69 self._contacts[contactId] = contactDetails
70 self.recipientsChanged.emit()
72 def remove_contact(self, contactId):
73 assert contactId in self._contacts
74 del self._contacts[contactId]
75 self.recipientsChanged.emit()
77 def get_contacts(self):
78 return self._contacts.iterkeys()
80 def get_num_contacts(self):
81 return len(self._contacts)
83 def get_title(self, cid):
84 return self._contacts[cid].title
86 def get_description(self, cid):
87 return self._contacts[cid].description
89 def get_numbers(self, cid):
90 return self._contacts[cid].numbers
92 def get_selected_number(self, cid):
93 return self._contacts[cid].selectedNumber
95 def set_selected_number(self, cid, number):
96 # @note I'm lazy, this isn't firing any kind of signal since only one
97 # controller right now and that is the viewer
98 assert number in (nWD[0] for nWD in self._contacts[cid].numbers)
99 self._contacts[cid].selectedNumber = number
102 oldContacts = self._contacts
105 self.recipientsChanged.emit()
107 def _send(self, numbers, text):
108 self.sendingMessage.emit()
111 self._backend[0].send_sms,
115 self.sentMessage.emit()
118 self.error.emit(str(e))
120 def _call(self, number):
124 self._backend[0].call,
131 self.error.emit(str(e))
134 self.cancelling.emit()
137 self._backend[0].cancel,
141 self.cancelled.emit()
143 self.error.emit(str(e))
146 class Session(QtCore.QObject):
148 stateChange = QtCore.pyqtSignal(str)
149 loggedOut = QtCore.pyqtSignal()
150 loggedIn = QtCore.pyqtSignal()
151 callbackNumberChanged = QtCore.pyqtSignal(str)
153 contactsUpdated = QtCore.pyqtSignal()
154 messagesUpdated = QtCore.pyqtSignal()
155 historyUpdated = QtCore.pyqtSignal()
156 dndStateChange = QtCore.pyqtSignal(bool)
158 error = QtCore.pyqtSignal(str)
160 LOGGEDOUT_STATE = "logged out"
161 LOGGINGIN_STATE = "logging in"
162 LOGGEDIN_STATE = "logged in"
164 _OLDEST_COMPATIBLE_FORMAT_VERSION = misc_utils.parse_version("1.2.0")
169 def __init__(self, cachePath = None):
170 QtCore.QObject.__init__(self)
171 self._pool = qore_utils.AsyncPool()
173 self._loggedInTime = self._LOGGEDOUT_TIME
175 self._cachePath = cachePath
176 self._username = None
177 self._draft = Draft(self._pool, self._backend)
188 self._LOGGEDOUT_TIME: self.LOGGEDOUT_STATE,
189 self._LOGGINGIN_TIME: self.LOGGINGIN_STATE,
190 }.get(self._loggedInTime, self.LOGGEDIN_STATE)
196 def login(self, username, password):
197 assert self.state == self.LOGGEDOUT_STATE
198 assert username != ""
199 if self._cachePath is not None:
200 cookiePath = os.path.join(self._cachePath, "%s.cookies" % username)
204 if self._username != username or not self._backend:
205 from backends import gv_backend
207 self._backend[0:0] = [gv_backend.GVDialer(cookiePath)]
210 le = concurrent.AsyncLinearExecution(self._pool, self._login)
211 le.start(username, password)
214 assert self.state != self.LOGGEDOUT_STATE
216 self._loggedInTime = self._LOGGEDOUT_TIME
217 self._backend[0].persist()
218 self._save_to_cache()
221 assert self.state == self.LOGGEDOUT_STATE
222 self._backend[0].logout()
227 def logout_and_clear(self):
228 assert self.state != self.LOGGEDOUT_STATE
230 self._loggedInTime = self._LOGGEDOUT_TIME
233 def update_contacts(self, force = True):
234 if not force and self._contacts:
236 le = concurrent.AsyncLinearExecution(self._pool, self._update_contacts)
237 self._perform_op_while_loggedin(le)
239 def get_contacts(self):
240 return self._contacts
242 def update_messages(self, force = True):
243 if not force and self._messages:
245 le = concurrent.AsyncLinearExecution(self._pool, self._update_messages)
246 self._perform_op_while_loggedin(le)
248 def get_messages(self):
249 return self._messages
251 def update_history(self, force = True):
252 if not force and self._history:
254 le = concurrent.AsyncLinearExecution(self._pool, self._update_history)
255 self._perform_op_while_loggedin(le)
257 def get_history(self):
260 def update_dnd(self):
261 le = concurrent.AsyncLinearExecution(self._pool, self._update_dnd)
262 self._perform_op_while_loggedin(le)
264 def set_dnd(self, dnd):
265 # I'm paranoid about our state geting out of sync so we set no matter
266 # what but act as if we have the cannonical state
267 assert self.state == self.LOGGEDIN_STATE
271 self._backend[0].set_dnd,
276 self.error.emit(str(e))
279 if oldDnd != self._dnd:
280 self.dndStateChange.emit(self._dnd)
285 def get_account_number(self):
286 return self._backend[0].get_account_number()
288 def get_callback_numbers(self):
289 # @todo Remove evilness
290 return self._backend[0].get_callback_numbers()
292 def get_callback_number(self):
293 return self._callback
295 def set_callback_number(self, callback):
296 # I'm paranoid about our state geting out of sync so we set no matter
297 # what but act as if we have the cannonical state
298 assert self.state == self.LOGGEDIN_STATE
299 oldCallback = self._callback
302 self._backend[0].set_callback_number,
307 self.error.emit(str(e))
309 self._callback = callback
310 if oldCallback != self._callback:
311 self.callbackNumberChanged.emit(self._callback)
313 def _login(self, username, password):
314 self._loggedInTime = self._LOGGINGIN_TIME
315 self.stateChange.emit(self.LOGGINGIN_STATE)
316 finalState = self.LOGGEDOUT_STATE
320 if not isLoggedIn and self._backend[0].is_quick_login_possible():
322 self._backend[0].is_authed,
327 _moduleLogger.info("Logged in through cookies")
329 # Force a clearing of the cookies
331 self._backend[0].logout,
338 self._backend[0].login,
339 (username, password),
343 _moduleLogger.info("Logged in through credentials")
346 self._loggedInTime = int(time.time())
347 oldUsername = self._username
348 self._username = username
349 finalState = self.LOGGEDIN_STATE
351 if oldUsername != self._username:
352 needOps = not self._load()
356 loginOps = self._loginOps[:]
359 del self._loginOps[:]
360 for asyncOp in loginOps:
363 self.error.emit(str(e))
365 self.stateChange.emit(finalState)
368 updateContacts = len(self._contacts) != 0
369 updateMessages = len(self._messages) != 0
370 updateHistory = len(self._history) != 0
372 oldCallback = self._callback
380 loadedFromCache = self._load_from_cache()
382 updateContacts = True
383 updateMessages = True
387 self.contactsUpdated.emit()
389 self.messagesUpdated.emit()
391 self.historyUpdated.emit()
392 if oldDnd != self._dnd:
393 self.dndStateChange.emit(self._dnd)
394 if oldCallback != self._callback:
395 self.callbackNumberChanged.emit(self._callback)
397 return loadedFromCache
399 def _load_from_cache(self):
400 if self._cachePath is None:
402 cachePath = os.path.join(self._cachePath, "%s.cache" % self._username)
405 with open(cachePath, "rb") as f:
406 dumpedData = pickle.load(f)
407 except (pickle.PickleError, IOError, EOFError, ValueError):
408 _moduleLogger.exception("Pickle fun loading")
411 _moduleLogger.exception("Weirdness loading")
416 contacts, messages, history, dnd, callback
419 if misc_utils.compare_versions(
420 self._OLDEST_COMPATIBLE_FORMAT_VERSION,
421 misc_utils.parse_version(version),
423 _moduleLogger.info("Loaded cache")
424 self._contacts = contacts
425 self._messages = messages
426 self._history = history
428 self._callback = callback
432 "Skipping cache due to version mismatch (%s-%s)" % (
438 def _save_to_cache(self):
439 _moduleLogger.info("Saving cache")
440 if self._cachePath is None:
442 cachePath = os.path.join(self._cachePath, "%s.cache" % self._username)
446 constants.__version__, constants.__build__,
447 self._contacts, self._messages, self._history, self._dnd, self._callback
449 with open(cachePath, "wb") as f:
450 pickle.dump(dataToDump, f, pickle.HIGHEST_PROTOCOL)
451 _moduleLogger.info("Cache saved")
452 except (pickle.PickleError, IOError):
453 _moduleLogger.exception("While saving")
455 def _clear_cache(self):
456 updateContacts = len(self._contacts) != 0
457 updateMessages = len(self._messages) != 0
458 updateHistory = len(self._history) != 0
460 oldCallback = self._callback
469 self.contactsUpdated.emit()
471 self.messagesUpdated.emit()
473 self.historyUpdated.emit()
474 if oldDnd != self._dnd:
475 self.dndStateChange.emit(self._dnd)
476 if oldCallback != self._callback:
477 self.callbackNumberChanged.emit(self._callback)
479 self._save_to_cache()
481 def _update_contacts(self):
483 self._contacts = yield (
484 self._backend[0].get_contacts,
489 self.error.emit(str(e))
491 self.contactsUpdated.emit()
493 def _update_messages(self):
495 self._messages = yield (
496 self._backend[0].get_messages,
501 self.error.emit(str(e))
503 self.messagesUpdated.emit()
505 def _update_history(self):
507 self._history = yield (
508 self._backend[0].get_recent,
513 self.error.emit(str(e))
515 self.historyUpdated.emit()
517 def _update_dnd(self):
521 self._backend[0].is_dnd,
526 self.error.emit(str(e))
528 if oldDnd != self._dnd:
529 self.dndStateChange(self._dnd)
531 def _perform_op_while_loggedin(self, op):
532 if self.state == self.LOGGEDIN_STATE:
535 self._push_login_op(op)
537 def _push_login_op(self, asyncOp):
538 assert self.state != self.LOGGEDIN_STATE
539 if asyncOp in self._loginOps:
540 _moduleLogger.info("Skipping queueing duplicate op: %r" % asyncOp)
542 self._loginOps.append(asyncOp)