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 # Allow overwriting of contacts so that the message can be updated and the SMS dialog popped back up
89 contactDetails = _DraftContact(title, description, numbersWithDescriptions)
90 self._contacts[contactId] = contactDetails
91 self.recipientsChanged.emit()
93 def remove_contact(self, contactId):
94 if self._busyReason is not None:
95 raise RuntimeError("Please wait for %r" % self._busyReason)
96 assert contactId in self._contacts, "Contact missing"
97 del self._contacts[contactId]
98 self.recipientsChanged.emit()
100 def get_contacts(self):
101 return self._contacts.iterkeys()
103 def get_num_contacts(self):
104 return len(self._contacts)
106 def get_title(self, cid):
107 return self._contacts[cid].title
109 def get_description(self, cid):
110 return self._contacts[cid].description
112 def get_numbers(self, cid):
113 return self._contacts[cid].numbers
115 def get_selected_number(self, cid):
116 return self._contacts[cid].selectedNumber
118 def set_selected_number(self, cid, number):
119 # @note I'm lazy, this isn't firing any kind of signal since only one
120 # controller right now and that is the viewer
121 assert number in (nWD[0] for nWD in self._contacts[cid].numbers), "Number not selectable"
122 self._contacts[cid].selectedNumber = number
125 if self._busyReason is not None:
126 raise RuntimeError("Please wait for %r" % self._busyReason)
130 oldContacts = self._contacts
134 self.recipientsChanged.emit()
136 @contextlib.contextmanager
137 def _busy(self, message):
138 if self._busyReason is not None:
139 raise RuntimeError("Already busy doing %r" % self._busyReason)
141 self._busyReason = message
144 self._busyReason = None
146 def _send(self, numbers, text):
147 self.sendingMessage.emit()
149 with self._busy("Sending Text"):
150 with qui_utils.notify_busy(self._errorLog, "Sending Text"):
152 self._backend[0].send_sms,
156 self.sentMessage.emit()
159 _moduleLogger.exception("Reporting error to user")
160 self.error.emit(str(e))
162 def _call(self, number):
165 with self._busy("Calling"):
166 with qui_utils.notify_busy(self._errorLog, "Calling"):
168 self._backend[0].call,
175 _moduleLogger.exception("Reporting error to user")
176 self.error.emit(str(e))
179 self.cancelling.emit()
181 with qui_utils.notify_busy(self._errorLog, "Cancelling"):
183 self._backend[0].cancel,
187 self.cancelled.emit()
189 _moduleLogger.exception("Reporting error to user")
190 self.error.emit(str(e))
193 class Session(QtCore.QObject):
195 # @todo Somehow add support for csv contacts
197 stateChange = QtCore.pyqtSignal(str)
198 loggedOut = QtCore.pyqtSignal()
199 loggedIn = QtCore.pyqtSignal()
200 callbackNumberChanged = QtCore.pyqtSignal(str)
202 contactsUpdated = QtCore.pyqtSignal()
203 messagesUpdated = QtCore.pyqtSignal()
204 historyUpdated = QtCore.pyqtSignal()
205 dndStateChange = QtCore.pyqtSignal(bool)
207 error = QtCore.pyqtSignal(str)
209 LOGGEDOUT_STATE = "logged out"
210 LOGGINGIN_STATE = "logging in"
211 LOGGEDIN_STATE = "logged in"
213 _OLDEST_COMPATIBLE_FORMAT_VERSION = misc_utils.parse_version("1.1.90")
218 def __init__(self, errorLog, cachePath = None):
219 QtCore.QObject.__init__(self)
220 self._errorLog = errorLog
221 self._pool = qore_utils.AsyncPool()
223 self._loggedInTime = self._LOGGEDOUT_TIME
225 self._cachePath = cachePath
226 self._username = None
227 self._draft = Draft(self._pool, self._backend, self._errorLog)
230 self._contactUpdateTime = datetime.datetime(1971, 1, 1)
232 self._messageUpdateTime = datetime.datetime(1971, 1, 1)
234 self._historyUpdateTime = datetime.datetime(1971, 1, 1)
241 self._LOGGEDOUT_TIME: self.LOGGEDOUT_STATE,
242 self._LOGGINGIN_TIME: self.LOGGINGIN_STATE,
243 }.get(self._loggedInTime, self.LOGGEDIN_STATE)
249 def login(self, username, password):
250 assert self.state == self.LOGGEDOUT_STATE, "Can only log-in when logged out (currently %s" % self.state
251 assert username != "", "No username specified"
252 if self._cachePath is not None:
253 cookiePath = os.path.join(self._cachePath, "%s.cookies" % username)
257 if self._username != username or not self._backend:
258 from backends import gv_backend
260 self._backend[0:0] = [gv_backend.GVDialer(cookiePath)]
263 le = concurrent.AsyncLinearExecution(self._pool, self._login)
264 le.start(username, password)
267 assert self.state != self.LOGGEDOUT_STATE, "Can only logout if logged in (currently %s" % self.state
268 _moduleLogger.info("Logging out")
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
285 _moduleLogger.info("Logging out and clearing the account")
287 self._loggedInTime = self._LOGGEDOUT_TIME
289 self.stateChange.emit(self.LOGGEDOUT_STATE)
290 self.loggedOut.emit()
292 def update_contacts(self, force = True):
293 if not force and self._contacts:
295 le = concurrent.AsyncLinearExecution(self._pool, self._update_contacts)
296 self._perform_op_while_loggedin(le)
298 def get_contacts(self):
299 return self._contacts
301 def get_when_contacts_updated(self):
302 return self._contactUpdateTime
304 def update_messages(self, force = True):
305 if not force and self._messages:
307 le = concurrent.AsyncLinearExecution(self._pool, self._update_messages)
308 self._perform_op_while_loggedin(le)
310 def get_messages(self):
311 return self._messages
313 def get_when_messages_updated(self):
314 return self._messageUpdateTime
316 def update_history(self, force = True):
317 if not force and self._history:
319 le = concurrent.AsyncLinearExecution(self._pool, self._update_history)
320 self._perform_op_while_loggedin(le)
322 def get_history(self):
325 def get_when_history_updated(self):
326 return self._historyUpdateTime
328 def update_dnd(self):
329 le = concurrent.AsyncLinearExecution(self._pool, self._update_dnd)
330 self._perform_op_while_loggedin(le)
332 def set_dnd(self, dnd):
333 le = concurrent.AsyncLinearExecution(self._pool, self._set_dnd)
336 def _set_dnd(self, dnd):
339 assert self.state == self.LOGGEDIN_STATE, "DND requires being logged in (currently %s" % self.state
340 with qui_utils.notify_busy(self._errorLog, "Setting DND Status"):
342 self._backend[0].set_dnd,
347 _moduleLogger.exception("Reporting error to user")
348 self.error.emit(str(e))
351 if oldDnd != self._dnd:
352 self.dndStateChange.emit(self._dnd)
357 def get_account_number(self):
358 if self.state != self.LOGGEDIN_STATE:
360 return self._backend[0].get_account_number()
362 def get_callback_numbers(self):
363 if self.state != self.LOGGEDIN_STATE:
365 return self._backend[0].get_callback_numbers()
367 def get_callback_number(self):
368 return self._callback
370 def set_callback_number(self, callback):
371 le = concurrent.AsyncLinearExecution(self._pool, self._set_callback_number)
374 def _set_callback_number(self, callback):
375 oldCallback = self._callback
377 assert self.state == self.LOGGEDIN_STATE, "Callbacks configurable only when logged in (currently %s" % self.state
379 self._backend[0].set_callback_number,
384 _moduleLogger.exception("Reporting error to user")
385 self.error.emit(str(e))
387 self._callback = callback
388 if oldCallback != self._callback:
389 self.callbackNumberChanged.emit(self._callback)
391 def _login(self, username, password):
392 with qui_utils.notify_busy(self._errorLog, "Logging In"):
393 self._loggedInTime = self._LOGGINGIN_TIME
394 self.stateChange.emit(self.LOGGINGIN_STATE)
395 finalState = self.LOGGEDOUT_STATE
398 if not isLoggedIn and self._backend[0].is_quick_login_possible():
400 self._backend[0].is_authed,
405 _moduleLogger.info("Logged in through cookies")
407 # Force a clearing of the cookies
409 self._backend[0].logout,
416 self._backend[0].login,
417 (username, password),
421 _moduleLogger.info("Logged in through credentials")
424 self._loggedInTime = int(time.time())
425 oldUsername = self._username
426 self._username = username
427 finalState = self.LOGGEDIN_STATE
428 if oldUsername != self._username:
429 needOps = not self._load()
434 self.stateChange.emit(finalState)
435 finalState = None # Mark it as already set
438 loginOps = self._loginOps[:]
441 del self._loginOps[:]
442 for asyncOp in loginOps:
445 self._loggedInTime = self._LOGGEDOUT_TIME
446 self.error.emit("Error logging in")
448 self._loggedInTime = self._LOGGEDOUT_TIME
449 _moduleLogger.exception("Reporting error to user")
450 self.error.emit(str(e))
452 if finalState is not None:
453 self.stateChange.emit(finalState)
454 if isLoggedIn and self._callback:
455 self.set_callback_number(self._callback)
458 updateContacts = len(self._contacts) != 0
459 updateMessages = len(self._messages) != 0
460 updateHistory = len(self._history) != 0
462 oldCallback = self._callback
470 loadedFromCache = self._load_from_cache()
472 updateContacts = True
473 updateMessages = True
477 self.contactsUpdated.emit()
479 self.messagesUpdated.emit()
481 self.historyUpdated.emit()
482 if oldDnd != self._dnd:
483 self.dndStateChange.emit(self._dnd)
484 if oldCallback != self._callback:
485 self.callbackNumberChanged.emit(self._callback)
487 return loadedFromCache
489 def _load_from_cache(self):
490 if self._cachePath is None:
492 cachePath = os.path.join(self._cachePath, "%s.cache" % self._username)
495 with open(cachePath, "rb") as f:
496 dumpedData = pickle.load(f)
497 except (pickle.PickleError, IOError, EOFError, ValueError):
498 _moduleLogger.exception("Pickle fun loading")
501 _moduleLogger.exception("Weirdness loading")
507 contacts, contactUpdateTime,
508 messages, messageUpdateTime,
509 history, historyUpdateTime,
513 _moduleLogger.exception("Upgrade/downgrade fun")
516 _moduleLogger.exception("Weirdlings")
518 if misc_utils.compare_versions(
519 self._OLDEST_COMPATIBLE_FORMAT_VERSION,
520 misc_utils.parse_version(version),
522 _moduleLogger.info("Loaded cache")
523 self._contacts = contacts
524 self._contactUpdateTime = contactUpdateTime
525 self._messages = messages
526 self._messageUpdateTime = messageUpdateTime
527 self._history = history
528 self._historyUpdateTime = historyUpdateTime
530 self._callback = callback
534 "Skipping cache due to version mismatch (%s-%s)" % (
540 def _save_to_cache(self):
541 _moduleLogger.info("Saving cache")
542 if self._cachePath is None:
544 cachePath = os.path.join(self._cachePath, "%s.cache" % self._username)
548 constants.__version__, constants.__build__,
549 self._contacts, self._contactUpdateTime,
550 self._messages, self._messageUpdateTime,
551 self._history, self._historyUpdateTime,
552 self._dnd, self._callback
554 with open(cachePath, "wb") as f:
555 pickle.dump(dataToDump, f, pickle.HIGHEST_PROTOCOL)
556 _moduleLogger.info("Cache saved")
557 except (pickle.PickleError, IOError):
558 _moduleLogger.exception("While saving")
560 def _clear_cache(self):
561 updateContacts = len(self._contacts) != 0
562 updateMessages = len(self._messages) != 0
563 updateHistory = len(self._history) != 0
565 oldCallback = self._callback
568 self._contactUpdateTime = datetime.datetime(1971, 1, 1)
570 self._messageUpdateTime = datetime.datetime(1971, 1, 1)
572 self._historyUpdateTime = datetime.datetime(1971, 1, 1)
577 self.contactsUpdated.emit()
579 self.messagesUpdated.emit()
581 self.historyUpdated.emit()
582 if oldDnd != self._dnd:
583 self.dndStateChange.emit(self._dnd)
584 if oldCallback != self._callback:
585 self.callbackNumberChanged.emit(self._callback)
587 self._save_to_cache()
589 def _update_contacts(self):
591 assert self.state == self.LOGGEDIN_STATE, "Contacts requires being logged in (currently %s" % self.state
592 with qui_utils.notify_busy(self._errorLog, "Updating Contacts"):
593 self._contacts = yield (
594 self._backend[0].get_contacts,
599 _moduleLogger.exception("Reporting error to user")
600 self.error.emit(str(e))
602 self._contactUpdateTime = datetime.datetime.now()
603 self.contactsUpdated.emit()
605 def _update_messages(self):
607 assert self.state == self.LOGGEDIN_STATE, "Messages requires being logged in (currently %s" % self.state
608 with qui_utils.notify_busy(self._errorLog, "Updating Messages"):
609 self._messages = yield (
610 self._backend[0].get_messages,
615 _moduleLogger.exception("Reporting error to user")
616 self.error.emit(str(e))
618 self._messageUpdateTime = datetime.datetime.now()
619 self.messagesUpdated.emit()
621 def _update_history(self):
623 assert self.state == self.LOGGEDIN_STATE, "History requires being logged in (currently %s" % self.state
624 with qui_utils.notify_busy(self._errorLog, "Updating History"):
625 self._history = yield (
626 self._backend[0].get_recent,
631 _moduleLogger.exception("Reporting error to user")
632 self.error.emit(str(e))
634 self._historyUpdateTime = datetime.datetime.now()
635 self.historyUpdated.emit()
637 def _update_dnd(self):
640 assert self.state == self.LOGGEDIN_STATE, "DND requires being logged in (currently %s" % self.state
642 self._backend[0].is_dnd,
647 _moduleLogger.exception("Reporting error to user")
648 self.error.emit(str(e))
650 if oldDnd != self._dnd:
651 self.dndStateChange(self._dnd)
653 def _perform_op_while_loggedin(self, op):
654 if self.state == self.LOGGEDIN_STATE:
657 self._push_login_op(op)
659 def _push_login_op(self, asyncOp):
660 assert self.state != self.LOGGEDIN_STATE, "Can only queue work when logged out"
661 if asyncOp in self._loginOps:
662 _moduleLogger.info("Skipping queueing duplicate op: %r" % asyncOp)
664 self._loginOps.append(asyncOp)