4 Grandcentral Dialer backend code
5 Eric Warnke <ericew@gmail.com>
15 from browser_emu import MozillaEmulator
18 class GCDialer(object):
20 This class encapsulates all of the knowledge necessary to interace with the grandcentral servers
21 the functions include login, setting up a callback number, and initalting a callback
24 _gcDialingStrRe = re.compile("This may take a few seconds", re.M) # string from Grandcentral.com on successful dial
25 _validateRe = re.compile("^[0-9]{10,}$")
26 _accessTokenRe = re.compile(r"""<input type="hidden" name="a_t" [^>]*value="(.*)"/>""")
27 _isLoginPageRe = re.compile(r"""<form method="post" action="https://www.grandcentral.com/mobile/account/login">""")
28 _callbackRe = re.compile(r"""name="default_number" value="(\d+)" />\s+(.*)\s$""", re.M)
29 _accountNumRe = re.compile(r"""<img src="/images/mobile/inbox_logo.gif" alt="GrandCentral" />\s*(.{14})\s* """, re.M)
30 _inboxRe = re.compile(r"""<td>.*?(voicemail|received|missed|call return).*?</td>\s+<td>\s+<font size="2">\s+(.*?)\s+ \| \s+<a href="/mobile/contacts/.*?">(.*?)\s?</a>\s+<br/>\s+(.*?)\s?<a href=""", re.S)
32 _forwardselectURL = "http://www.grandcentral.com/mobile/settings/forwarding_select"
33 _loginURL = "https://www.grandcentral.com/mobile/account/login"
34 _setforwardURL = "http://www.grandcentral.com/mobile/settings/set_forwarding?from=settings"
35 _clicktocallURL = "http://www.grandcentral.com/mobile/calls/click_to_call?a_t=%s&destno=%s"
36 _inboxallURL = "http://www.grandcentral.com/mobile/messages/inbox?types=all"
38 def __init__(self, cookieFile = None):
39 # Important items in this function are the setup of the browser emulation and cookie file
41 if cookieFile is None:
42 cookieFile = os.path.join(os.path.expanduser("~"), ".gc_dialer_cookies.txt")
43 self._browser = MozillaEmulator(None, 0)
44 self._browser.cookies.filename = cookieFile
45 if os.path.isfile(cookieFile):
46 self._browser.cookies.load()
48 # self._browser.cookies.save()
50 self._accessToken = None
51 self._accountNum = None
52 self._callbackNumbers = {}
53 self._lastAuthed = 0.0
55 def grabToken(self, data):
56 "Pull the magic cookie from the datastream"
57 atGroup = GCDialer._accessTokenRe.search(data)
59 self._accessToken = atGroup.group(1)
63 anGroup = GCDialer._accountNumRe.search(data)
65 self._accountNum = anGroup.group(1)
69 self._callbackNumbers = {}
71 for match in GCDialer._callbackRe.finditer(data):
72 self._callbackNumbers[match.group(1)] = match.group(2)
76 def getAccountNumber(self):
77 return self._accountNum
79 def isAuthed(self, force = False):
81 Attempts to detect a current session and pull the
82 auth token ( a_t ) from the page. Once logged in
83 try not to reauth more than once a minute.
87 if time.time() - self._lastAuthed < 60 and not force:
91 self._lastData = self._browser.download(GCDialer._forwardselectURL)
92 self._browser.cookies.save()
93 if GCDialer._isLoginPageRe.search(self._lastData) is None:
94 self.grabToken(self._lastData)
95 self._lastAuthed = time.time()
101 def login(self, username, password):
103 Attempt to login to grandcentral
108 loginPostData = urllib.urlencode( {'username' : username , 'password' : password } )
109 self._lastData = self._browser.download(GCDialer._loginURL, loginPostData)
110 return self.isAuthed()
115 def setSaneCallback(self):
117 Try to set a sane default callback number on these preferences
118 1) 1747 numbers ( Gizmo )
119 2) anything with gizmo in the name
120 3) anything with computer in the name
123 numbers = self.getCallbackNumbers()
125 for number, description in numbers.iteritems():
126 if not re.compile(r"""1747""").match(number) is None:
127 self.setCallbackNumber(number)
130 for number, description in numbers.iteritems():
131 if not re.compile(r"""gizmo""", re.I).search(description) is None:
132 self.setCallbackNumber(number)
135 for number, description in numbers.iteritems():
136 if not re.compile(r"""computer""", re.I).search(description) is None:
137 self.setCallbackNumber(number)
140 for number, description in numbers.iteritems():
141 self.setCallbackNumber(number)
144 def getCallbackNumbers(self):
146 @returns a dictionary mapping call back numbers to descriptions. These results
147 are cached for 30 minutes.
149 if time.time() - self._lastAuthed < 1800 or self.isAuthed():
150 return self._callbackNumbers
154 def setCallbackNumber(self, callbacknumber):
156 set the number that grandcental calls
157 this should be a proper 10 digit number
160 callbackPostData = urllib.urlencode({'a_t' : self._accessToken, 'default_number' : callbacknumber })
161 self._lastData = self._browser.download(GCDialer._setforwardURL, callbackPostData)
162 self._browser.cookies.save()
166 def getCallbackNumber(self):
167 for c in self._browser.cookies:
168 if c.name == "pda_forwarding_number":
173 self._browser.cookies.clear()
174 self._browser.cookies.save()
176 def validate(self, number):
178 Can this number be called ( syntax validation only )
180 return GCDialer._validateRe.match(number) is not None
182 def dial(self, number):
184 This is the main function responsible for initating the callback
186 # If the number is not valid throw exception
187 if self.validate(number) is False:
188 raise ValueError('number is not valid')
190 # No point if we don't have the magic cookie
191 if not self.isAuthed():
194 # Strip leading 1 from 11 digit dialing
195 if len(number) == 11 and number[0] == 1:
199 self._lastData = self._browser.download(
200 GCDialer._clicktocallURL % (self._accessToken, number),
201 None, {'Referer' : 'http://www.grandcentral.com/mobile/messages'} )
203 if GCDialer._gcDialingStrRe.search(self._lastData) is not None:
211 def get_recent(self):
213 self._lastData = self._browser.download(GCDialer._inboxallURL)
214 for match in self._inboxRe.finditer(self._lastData):
215 yield (match.group(4), "%s on %s from/to %s - %s" % (match.group(1).capitalize(), match.group(2), match.group(3), match.group(4)))