1 from __future__ import with_statement
15 from PyQt4 import QtCore
17 from util import qore_utils
18 from util import qui_utils
19 from util import concurrent
20 from util import misc as misc_utils
25 _moduleLogger = logging.getLogger(__name__)
28 class _DraftContact(object):
30 def __init__(self, title, description, numbersWithDescriptions):
32 self.description = description
33 self.numbers = numbersWithDescriptions
34 self.selectedNumber = numbersWithDescriptions[0][0]
37 class Draft(QtCore.QObject):
39 sendingMessage = QtCore.pyqtSignal()
40 sentMessage = QtCore.pyqtSignal()
41 calling = QtCore.pyqtSignal()
42 called = QtCore.pyqtSignal()
43 cancelling = QtCore.pyqtSignal()
44 cancelled = QtCore.pyqtSignal()
45 error = QtCore.pyqtSignal(str)
47 recipientsChanged = QtCore.pyqtSignal()
49 def __init__(self, pool, backend, errorLog):
50 QtCore.QObject.__init__(self)
51 self._errorLog = errorLog
54 self._backend = backend
55 self._busyReason = None
59 assert 0 < len(self._contacts), "No contacts selected"
60 assert 0 < len(self._message), "No message to send"
61 numbers = [misc_utils.make_ugly(contact.selectedNumber) for contact in self._contacts.itervalues()]
62 le = concurrent.AsyncLinearExecution(self._pool, self._send)
63 le.start(numbers, self._message)
66 assert len(self._contacts) == 1, "Must select 1 and only 1 contact"
67 assert len(self._message) == 0, "Cannot send message with call"
68 (contact, ) = self._contacts.itervalues()
69 number = misc_utils.make_ugly(contact.selectedNumber)
70 le = concurrent.AsyncLinearExecution(self._pool, self._call)
74 le = concurrent.AsyncLinearExecution(self._pool, self._cancel)
77 def _get_message(self):
80 def _set_message(self, message):
81 self._message = message
83 message = property(_get_message, _set_message)
85 def add_contact(self, contactId, title, description, numbersWithDescriptions):
86 if self._busyReason is not None:
87 raise RuntimeError("Please wait for %r" % self._busyReason)
88 if contactId in self._contacts:
89 _moduleLogger.info("Adding duplicate contact %r" % contactId)
90 # @todo Remove this evil hack to re-popup the dialog
91 self.recipientsChanged.emit()
93 contactDetails = _DraftContact(title, description, numbersWithDescriptions)
94 self._contacts[contactId] = contactDetails
95 self.recipientsChanged.emit()
97 def remove_contact(self, contactId):
98 if self._busyReason is not None:
99 raise RuntimeError("Please wait for %r" % self._busyReason)
100 assert contactId in self._contacts, "Contact missing"
101 del self._contacts[contactId]
102 self.recipientsChanged.emit()
104 def get_contacts(self):
105 return self._contacts.iterkeys()
107 def get_num_contacts(self):
108 return len(self._contacts)
110 def get_title(self, cid):
111 return self._contacts[cid].title
113 def get_description(self, cid):
114 return self._contacts[cid].description
116 def get_numbers(self, cid):
117 return self._contacts[cid].numbers
119 def get_selected_number(self, cid):
120 return self._contacts[cid].selectedNumber
122 def set_selected_number(self, cid, number):
123 # @note I'm lazy, this isn't firing any kind of signal since only one
124 # controller right now and that is the viewer
125 assert number in (nWD[0] for nWD in self._contacts[cid].numbers), "Number not selectable"
126 self._contacts[cid].selectedNumber = number
129 if self._busyReason is not None:
130 raise RuntimeError("Please wait for %r" % self._busyReason)
134 oldContacts = self._contacts
138 self.recipientsChanged.emit()
140 @contextlib.contextmanager
141 def _busy(self, message):
142 if self._busyReason is not None:
143 raise RuntimeError("Already busy doing %r" % self._busyReason)
145 self._busyReason = message
148 self._busyReason = None
150 def _send(self, numbers, text):
151 self.sendingMessage.emit()
153 with self._busy("Sending Text"):
154 with qui_utils.notify_busy(self._errorLog, "Sending Text"):
156 self._backend[0].send_sms,
160 self.sentMessage.emit()
163 self.error.emit(str(e))
165 def _call(self, number):
168 with self._busy("Calling"):
169 with qui_utils.notify_busy(self._errorLog, "Calling"):
171 self._backend[0].call,
178 self.error.emit(str(e))
181 self.cancelling.emit()
183 with qui_utils.notify_busy(self._errorLog, "Cancelling"):
185 self._backend[0].cancel,
189 self.cancelled.emit()
191 self.error.emit(str(e))
194 class Session(QtCore.QObject):
196 # @todo Somehow add support for csv contacts
198 stateChange = QtCore.pyqtSignal(str)
199 loggedOut = QtCore.pyqtSignal()
200 loggedIn = QtCore.pyqtSignal()
201 callbackNumberChanged = QtCore.pyqtSignal(str)
203 contactsUpdated = QtCore.pyqtSignal()
204 messagesUpdated = QtCore.pyqtSignal()
205 historyUpdated = QtCore.pyqtSignal()
206 dndStateChange = QtCore.pyqtSignal(bool)
208 error = QtCore.pyqtSignal(str)
210 LOGGEDOUT_STATE = "logged out"
211 LOGGINGIN_STATE = "logging in"
212 LOGGEDIN_STATE = "logged in"
214 _OLDEST_COMPATIBLE_FORMAT_VERSION = misc_utils.parse_version("1.1.90")
219 def __init__(self, errorLog, cachePath = None):
220 QtCore.QObject.__init__(self)
221 self._errorLog = errorLog
222 self._pool = qore_utils.AsyncPool()
224 self._loggedInTime = self._LOGGEDOUT_TIME
226 self._cachePath = cachePath
227 self._username = None
228 self._draft = Draft(self._pool, self._backend, self._errorLog)
231 self._contactUpdateTime = datetime.datetime(1971, 1, 1)
233 self._messageUpdateTime = datetime.datetime(1971, 1, 1)
235 self._historyUpdateTime = datetime.datetime(1971, 1, 1)
242 self._LOGGEDOUT_TIME: self.LOGGEDOUT_STATE,
243 self._LOGGINGIN_TIME: self.LOGGINGIN_STATE,
244 }.get(self._loggedInTime, self.LOGGEDIN_STATE)
250 def login(self, username, password):
251 assert self.state == self.LOGGEDOUT_STATE, "Can only log-in when logged out (currently %s" % self.state
252 assert username != "", "No username specified"
253 if self._cachePath is not None:
254 cookiePath = os.path.join(self._cachePath, "%s.cookies" % username)
258 if self._username != username or not self._backend:
259 from backends import gv_backend
261 self._backend[0:0] = [gv_backend.GVDialer(cookiePath)]
264 le = concurrent.AsyncLinearExecution(self._pool, self._login)
265 le.start(username, password)
268 assert self.state != self.LOGGEDOUT_STATE, "Can only logout if logged in (currently %s" % self.state
270 self._loggedInTime = self._LOGGEDOUT_TIME
271 self._backend[0].persist()
272 self._save_to_cache()
273 self.stateChange.emit(self.LOGGEDOUT_STATE)
274 self.loggedOut.emit()
277 assert self.state == self.LOGGEDOUT_STATE, "Can only clear when logged out (currently %s" % self.state
278 self._backend[0].logout()
283 def logout_and_clear(self):
284 assert self.state != self.LOGGEDOUT_STATE, "Can only logout if logged in (currently %s" % self.state
286 self._loggedInTime = self._LOGGEDOUT_TIME
288 self.stateChange.emit(self.LOGGEDOUT_STATE)
289 self.loggedOut.emit()
291 def update_contacts(self, force = True):
292 if not force and self._contacts:
294 le = concurrent.AsyncLinearExecution(self._pool, self._update_contacts)
295 self._perform_op_while_loggedin(le)
297 def get_contacts(self):
298 return self._contacts
300 def get_when_contacts_updated(self):
301 return self._contactUpdateTime
303 def update_messages(self, force = True):
304 if not force and self._messages:
306 le = concurrent.AsyncLinearExecution(self._pool, self._update_messages)
307 self._perform_op_while_loggedin(le)
309 def get_messages(self):
310 return self._messages
312 def get_when_messages_updated(self):
313 return self._messageUpdateTime
315 def update_history(self, force = True):
316 if not force and self._history:
318 le = concurrent.AsyncLinearExecution(self._pool, self._update_history)
319 self._perform_op_while_loggedin(le)
321 def get_history(self):
324 def get_when_history_updated(self):
325 return self._historyUpdateTime
327 def update_dnd(self):
328 le = concurrent.AsyncLinearExecution(self._pool, self._update_dnd)
329 self._perform_op_while_loggedin(le)
331 def set_dnd(self, dnd):
332 le = concurrent.AsyncLinearExecution(self._pool, self._set_dnd)
335 def _set_dnd(self, dnd):
336 # I'm paranoid about our state geting out of sync so we set no matter
337 # what but act as if we have the cannonical state
338 assert self.state == self.LOGGEDIN_STATE, "DND requires being logged in (currently %s" % self.state
341 with qui_utils.notify_busy(self._errorLog, "Setting DND Status"):
343 self._backend[0].set_dnd,
348 self.error.emit(str(e))
351 if oldDnd != self._dnd:
352 self.dndStateChange.emit(self._dnd)
357 def get_account_number(self):
358 return self._backend[0].get_account_number()
360 def get_callback_numbers(self):
361 # @todo Remove evilness (might call is_authed which can block)
362 return self._backend[0].get_callback_numbers()
364 def get_callback_number(self):
365 return self._callback
367 def set_callback_number(self, callback):
368 le = concurrent.AsyncLinearExecution(self._pool, self._set_callback_number)
371 def _set_callback_number(self, callback):
372 # I'm paranoid about our state geting out of sync so we set no matter
373 # what but act as if we have the cannonical state
374 assert self.state == self.LOGGEDIN_STATE, "Callbacks configurable only when logged in (currently %s" % self.state
375 oldCallback = self._callback
378 self._backend[0].set_callback_number,
383 self.error.emit(str(e))
385 self._callback = callback
386 if oldCallback != self._callback:
387 self.callbackNumberChanged.emit(self._callback)
389 def _login(self, username, password):
390 with qui_utils.notify_busy(self._errorLog, "Logging In"):
391 self._loggedInTime = self._LOGGINGIN_TIME
392 self.stateChange.emit(self.LOGGINGIN_STATE)
393 finalState = self.LOGGEDOUT_STATE
396 if not isLoggedIn and self._backend[0].is_quick_login_possible():
398 self._backend[0].is_authed,
403 _moduleLogger.info("Logged in through cookies")
405 # Force a clearing of the cookies
407 self._backend[0].logout,
414 self._backend[0].login,
415 (username, password),
419 _moduleLogger.info("Logged in through credentials")
422 self._loggedInTime = int(time.time())
423 oldUsername = self._username
424 self._username = username
425 finalState = self.LOGGEDIN_STATE
426 if oldUsername != self._username:
427 needOps = not self._load()
432 self.stateChange.emit(finalState)
433 finalState = None # Mark it as already set
436 loginOps = self._loginOps[:]
439 del self._loginOps[:]
440 for asyncOp in loginOps:
443 self._loggedInTime = self._LOGGEDOUT_TIME
444 self.error.emit("Error logging in")
446 self._loggedInTime = self._LOGGEDOUT_TIME
447 self.error.emit(str(e))
449 if finalState is not None:
450 self.stateChange.emit(finalState)
451 if isLoggedIn and self._callback:
452 self.set_callback_number(self._callback)
455 updateContacts = len(self._contacts) != 0
456 updateMessages = len(self._messages) != 0
457 updateHistory = len(self._history) != 0
459 oldCallback = self._callback
467 loadedFromCache = self._load_from_cache()
469 updateContacts = True
470 updateMessages = True
474 self.contactsUpdated.emit()
476 self.messagesUpdated.emit()
478 self.historyUpdated.emit()
479 if oldDnd != self._dnd:
480 self.dndStateChange.emit(self._dnd)
481 if oldCallback != self._callback:
482 self.callbackNumberChanged.emit(self._callback)
484 return loadedFromCache
486 def _load_from_cache(self):
487 if self._cachePath is None:
489 cachePath = os.path.join(self._cachePath, "%s.cache" % self._username)
492 with open(cachePath, "rb") as f:
493 dumpedData = pickle.load(f)
494 except (pickle.PickleError, IOError, EOFError, ValueError):
495 _moduleLogger.exception("Pickle fun loading")
498 _moduleLogger.exception("Weirdness loading")
503 contacts, contactUpdateTime,
504 messages, messageUpdateTime,
505 history, historyUpdateTime,
509 if misc_utils.compare_versions(
510 self._OLDEST_COMPATIBLE_FORMAT_VERSION,
511 misc_utils.parse_version(version),
513 _moduleLogger.info("Loaded cache")
514 self._contacts = contacts
515 self._contactUpdateTime = contactUpdateTime
516 self._messages = messages
517 self._messageUpdateTime = messageUpdateTime
518 self._history = history
519 self._historyUpdateTime = historyUpdateTime
521 self._callback = callback
525 "Skipping cache due to version mismatch (%s-%s)" % (
531 def _save_to_cache(self):
532 _moduleLogger.info("Saving cache")
533 if self._cachePath is None:
535 cachePath = os.path.join(self._cachePath, "%s.cache" % self._username)
539 constants.__version__, constants.__build__,
540 self._contacts, self._contactUpdateTime,
541 self._messages, self._messageUpdateTime,
542 self._history, self._historyUpdateTime,
543 self._dnd, self._callback
545 with open(cachePath, "wb") as f:
546 pickle.dump(dataToDump, f, pickle.HIGHEST_PROTOCOL)
547 _moduleLogger.info("Cache saved")
548 except (pickle.PickleError, IOError):
549 _moduleLogger.exception("While saving")
551 def _clear_cache(self):
552 updateContacts = len(self._contacts) != 0
553 updateMessages = len(self._messages) != 0
554 updateHistory = len(self._history) != 0
556 oldCallback = self._callback
559 self._contactUpdateTime = datetime.datetime(1971, 1, 1)
561 self._messageUpdateTime = datetime.datetime(1971, 1, 1)
563 self._historyUpdateTime = datetime.datetime(1971, 1, 1)
568 self.contactsUpdated.emit()
570 self.messagesUpdated.emit()
572 self.historyUpdated.emit()
573 if oldDnd != self._dnd:
574 self.dndStateChange.emit(self._dnd)
575 if oldCallback != self._callback:
576 self.callbackNumberChanged.emit(self._callback)
578 self._save_to_cache()
580 def _update_contacts(self):
582 with qui_utils.notify_busy(self._errorLog, "Updating Contacts"):
583 self._contacts = yield (
584 self._backend[0].get_contacts,
589 self.error.emit(str(e))
591 self._contactUpdateTime = datetime.datetime.now()
592 self.contactsUpdated.emit()
594 def _update_messages(self):
596 with qui_utils.notify_busy(self._errorLog, "Updating Messages"):
597 self._messages = yield (
598 self._backend[0].get_messages,
603 self.error.emit(str(e))
605 self._messageUpdateTime = datetime.datetime.now()
606 self.messagesUpdated.emit()
608 def _update_history(self):
610 with qui_utils.notify_busy(self._errorLog, "Updating History"):
611 self._history = yield (
612 self._backend[0].get_recent,
617 self.error.emit(str(e))
619 self._historyUpdateTime = datetime.datetime.now()
620 self.historyUpdated.emit()
622 def _update_dnd(self):
626 self._backend[0].is_dnd,
631 self.error.emit(str(e))
633 if oldDnd != self._dnd:
634 self.dndStateChange(self._dnd)
636 def _perform_op_while_loggedin(self, op):
637 if self.state == self.LOGGEDIN_STATE:
640 self._push_login_op(op)
642 def _push_login_op(self, asyncOp):
643 assert self.state != self.LOGGEDIN_STATE, "Can only queue work when logged out"
644 if asyncOp in self._loginOps:
645 _moduleLogger.info("Skipping queueing duplicate op: %r" % asyncOp)
647 self._loginOps.append(asyncOp)