Adding gc_backend tests
[gc-dialer] / src / gc_backend.py
index f664ca4..ec02e90 100644 (file)
@@ -1,23 +1,23 @@
 #!/usr/bin/python
 
-# DialCentral - Front end for Google's Grand Central service.
-# Copyright (C) 2008  Eric Warnke ericew AT gmail DOT com
-# 
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-# 
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-# Lesser General Public License for more details.
-# 
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
-
 """
+DialCentral - Front end for Google's Grand Central service.
+Copyright (C) 2008  Eric Warnke ericew AT gmail DOT com
+
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
+
 Grandcentral backend code
 """
 
@@ -29,8 +29,9 @@ import urllib2
 import time
 import warnings
 import traceback
+from xml.sax import saxutils
 
-from browser_emu import MozillaEmulator
+import browser_emu
 
 
 class GCDialer(object):
@@ -43,7 +44,7 @@ class GCDialer(object):
        _accessTokenRe = re.compile(r"""<input type="hidden" name="a_t" [^>]*value="(.*)"/>""")
        _isLoginPageRe = re.compile(r"""<form method="post" action="https://www.grandcentral.com/mobile/account/login">""")
        _callbackRe = re.compile(r"""name="default_number" value="(\d+)" />\s+(.*)\s$""", re.M)
-       _accountNumRe = re.compile(r"""<img src="/images/mobile/inbox_logo.gif" alt="GrandCentral" />\s*(.{14})\s*&nbsp""", re.M)
+       _accountNumRe = re.compile(r"""<input type="hidden" name="gcentral_num" [^>]*value="(.*)"/>""")
        _inboxRe = re.compile(r"""<td>.*?(voicemail|received|missed|call return).*?</td>\s+<td>\s+<font size="2">\s+(.*?)\s+&nbsp;\|&nbsp;\s+<a href="/mobile/contacts/.*?">(.*?)\s?</a>\s+<br/>\s+(.*?)\s?<a href=""", re.S)
        _contactsRe = re.compile(r"""<a href="/mobile/contacts/detail/(\d+)">(.*?)</a>""", re.S)
        _contactsNextRe = re.compile(r""".*<a href="/mobile/contacts(\?page=\d+)">Next</a>""", re.S)
@@ -61,7 +62,7 @@ class GCDialer(object):
 
        def __init__(self, cookieFile = None):
                # Important items in this function are the setup of the browser emulation and cookie file
-               self._browser = MozillaEmulator(None, 0)
+               self._browser = browser_emu.MozillaEmulator(1)
                if cookieFile is None:
                        cookieFile = os.path.join(os.path.expanduser("~"), ".gc_cookies.txt")
                self._browser.cookies.filename = cookieFile
@@ -69,9 +70,9 @@ class GCDialer(object):
                        self._browser.cookies.load()
 
                self._accessToken = None
-               self._accountNum = None
-               self._callbackNumbers = {}
+               self._accountNum = ""
                self._lastAuthed = 0.0
+               self._callbackNumbers = {}
 
                self.__contacts = None
 
@@ -89,13 +90,18 @@ class GCDialer(object):
                        forwardSelectionPage = self._browser.download(self._forwardselectURL)
                except urllib2.URLError, e:
                        warnings.warn(traceback.format_exc())
-                       raise RuntimeError("%s is not accesible" % self._forwardselectURL)
+                       return False
 
-               self._browser.cookies.save()
                if self._isLoginPageRe.search(forwardSelectionPage) is not None:
                        return False
 
-               self._grab_token(forwardSelectionPage)
+               try:
+                       self._grab_token(forwardSelectionPage)
+               except StandardError, e:
+                       warnings.warn(traceback.format_exc())
+                       return False
+
+               self._browser.cookies.save()
                self._lastAuthed = time.time()
                return True
 
@@ -152,6 +158,9 @@ class GCDialer(object):
 
                return True
 
+       def send_sms(self, number, message):
+               raise NotImplementedError("SMS Is Not Supported by GrandCentral")
+
        def clear_caches(self):
                self.__contacts = None
 
@@ -231,7 +240,7 @@ class GCDialer(object):
                for c in self._browser.cookies:
                        if c.name == "pda_forwarding_number":
                                return c.value
-               return None
+               return ""
 
        def get_recent(self):
                """
@@ -245,9 +254,9 @@ class GCDialer(object):
 
                for match in self._inboxRe.finditer(recentCallsPage):
                        phoneNumber = match.group(4)
-                       action = match.group(1)
-                       date = match.group(2)
-                       personsName = match.group(3)
+                       action = saxutils.unescape(match.group(1))
+                       date = saxutils.unescape(match.group(2))
+                       personsName = saxutils.unescape(match.group(3))
                        yield personsName, phoneNumber, date, action
 
        def get_addressbooks(self):
@@ -284,7 +293,7 @@ class GCDialer(object):
                                for contact_match in self._contactsRe.finditer(contactsPage):
                                        contactId = contact_match.group(1)
                                        contactName = contact_match.group(2)
-                                       contact = contactId, contactName
+                                       contact = contactId, saxutils.unescape(contactName)
                                        self.__contacts.append(contact)
                                        yield contact
 
@@ -307,10 +316,13 @@ class GCDialer(object):
                        raise RuntimeError("%s is not accesible" % self._contactDetailURL)
 
                for detail_match in self._contactDetailPhoneRe.finditer(detailPage):
-                       phoneType = detail_match.group(1)
+                       phoneType = saxutils.unescape(detail_match.group(1))
                        phoneNumber = detail_match.group(2)
                        yield (phoneType, phoneNumber)
 
+       def get_messages(self):
+               return ()
+
        def _grab_token(self, data):
                "Pull the magic cookie from the datastream"
                atGroup = self._accessTokenRe.search(data)
@@ -319,9 +331,10 @@ class GCDialer(object):
                self._accessToken = atGroup.group(1)
 
                anGroup = self._accountNumRe.search(data)
-               if atGroup is None:
-                       raise RuntimeError("Could not extract account number from GrandCentral")
-               self._accountNum = anGroup.group(1)
+               if anGroup is not None:
+                       self._accountNum = anGroup.group(1)
+               else:
+                       warnings.warn("Could not extract account number from GrandCentral", UserWarning, 2)
 
                self._callbackNumbers = {}
                for match in self._callbackRe.finditer(data):
@@ -334,7 +347,7 @@ def test_backend(username, password):
        print "Authenticated: ", backend.is_authed()
        print "Login?: ", backend.login(username, password)
        print "Authenticated: ", backend.is_authed()
-       print "Token: ", backend._token
+       # print "Token: ", backend._accessToken
        print "Account: ", backend.get_account_number()
        print "Callback: ", backend.get_callback_number()
        # print "All Callback: ",