try blocks, cached authentication returns
[gc-dialer] / gc_dialer / gcbackend.py
1 #!/usr/bin/python
2
3 """
4 Grandcentral Dialer backend code
5 Eric Warnke <ericew@gmail.com>
6 Copyright 2008 GPLv2
7 """
8
9
10 import os
11 import re
12 import urllib
13 import time
14
15 from browser_emu import MozillaEmulator
16
17
18 class GCDialer(object):
19         """
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
22         """
23
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*&nbsp""", re.M)
30         _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)
31
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"
37
38         def __init__(self, cookieFile = None):
39                 # Important items in this function are the setup of the browser emulation and cookie file
40                 self._msg = ""
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()
47                 #else:
48                 #       self._browser.cookies.save()
49                 self._lastData = ""
50                 self._accessToken = None
51                 self._accountNum = None
52                 self._lastAuthed = 0.0
53
54         def grabToken(self, data):
55                 "Pull the magic cookie from the datastream"
56                 atGroup = GCDialer._accessTokenRe.search(data)
57                 try:
58                         self._accessToken = atGroup.group(1)
59                 except:
60                         pass
61
62                 anGroup = GCDialer._accountNumRe.search(data)
63                 try:
64                         self._accountNum = anGroup.group(1)
65                 except:
66                         pass
67
68         def getAccountNumber(self):
69                 return self._accountNum
70
71         def isAuthed(self, force = False):
72                 """
73                 Attempts to detect a current session and pull the
74                 auth token ( a_t ) from the page.  Once logged in
75                 try not to reauth more than once a minute.
76                 """
77         
78                 if time.time() - self._lastAuthed < 60 and not force:
79                         return True
80
81                 try:    
82                         self._lastData = self._browser.download(GCDialer._forwardselectURL)
83                         self._browser.cookies.save()
84                         if GCDialer._isLoginPageRe.search(self._lastData) is None:
85                                 self.grabToken(self._lastData)
86                                 self.lastAuthed = time.time()
87                                 return True
88                 except:
89                         pass
90                 return False
91
92         def login(self, username, password):
93                 """
94                 Attempt to login to grandcentral
95                 """
96                 try:
97                         if self.isAuthed():
98                                 return
99                         loginPostData = urllib.urlencode( {'username' : username , 'password' : password } )
100                         self._lastData = self._browser.download(GCDialer._loginURL, loginPostData)
101                         return self.isAuthed()
102                 except:
103                         pass
104                 return False
105
106         def setSaneCallback(self):
107                 """
108                 Try to set a sane default callback number on these preferences
109                 1) 1747 numbers ( Gizmo )
110                 2) anything with gizmo in the name
111                 3) anything with computer in the name
112                 4) the first value
113                 """
114                 numbers = self.getCallbackNumbers()
115
116                 for number, description in numbers.iteritems():
117                         if not re.compile(r"""1747""").match(number) is None:
118                                 self.setCallbackNumber(number)
119                                 return
120
121                 for number, description in numbers.iteritems():
122                         if not re.compile(r"""gizmo""", re.I).search(description) is None:
123                                 self.setCallbackNumber(number)
124                                 return
125
126                 for number, description in numbers.iteritems():
127                         if not re.compile(r"""computer""", re.I).search(description) is None:
128                                 self.setCallbackNumber(number)
129                                 return
130
131                 for number, description in numbers.iteritems():
132                         self.setCallbackNumber(number)
133                         return
134
135         def getCallbackNumbers(self):
136                 """
137                 @returns a dictionary mapping call back numbers to descriptions
138                 """
139                 retval = {}
140         
141                 try:
142                         self._lastData = self._browser.download(GCDialer._forwardselectURL)
143                         for match in GCDialer._callbackRe.finditer(self._lastData):
144                                 retval[match.group(1)] = match.group(2)
145                 except:
146                         pass
147
148                 return retval
149
150         def setCallbackNumber(self, callbacknumber):
151                 """
152                 set the number that grandcental calls
153                 this should be a proper 10 digit number
154                 """
155                 try:
156                         callbackPostData = urllib.urlencode({'a_t' : self._accessToken, 'default_number' : callbacknumber })
157                         self._lastData = self._browser.download(GCDialer._setforwardURL, callbackPostData)
158                         self._browser.cookies.save()
159                 except:
160                         pass
161
162         def getCallbackNumber(self):
163                 for c in self._browser.cookies:
164                         if c.name == "pda_forwarding_number":
165                                 return c.value
166                 return None
167
168         def reset(self):
169                 self._browser.cookies.clear()
170                 self._browser.cookies.save()
171
172         def validate(self, number):
173                 """
174                 Can this number be called ( syntax validation only )
175                 """
176                 return GCDialer._validateRe.match(number) is not None
177
178         def dial(self, number):
179                 """
180                 This is the main function responsible for initating the callback
181                 """
182                 # If the number is not valid throw exception
183                 if self.validate(number) is False:
184                         raise ValueError('number is not valid')
185
186                 # No point if we don't have the magic cookie
187                 if not self.isAuthed():
188                         return False
189
190                 # Strip leading 1 from 11 digit dialing
191                 if len(number) == 11 and number[0] == 1:
192                         number = number[1:]
193
194                 try:
195                         self._lastData = self._browser.download(
196                                 GCDialer._clicktocallURL % (self._accessToken, number),
197                                 None, {'Referer' : 'http://www.grandcentral.com/mobile/messages'} )
198
199                         if GCDialer._gcDialingStrRe.search(self._lastData) is not None:
200                                 return True
201                         else:
202                                 return False
203                 except:
204                         pass
205                 return False
206
207         def get_recent(self):
208                 try:
209                         retval = []
210                         self._lastData = self._browser.download(GCDialer._inboxallURL)
211                         for match in self._inboxRe.finditer(self._lastData):
212                                 retval.append([match.group(4), "%s on %s from/to %s - %s" % (match.group(1).capitalize(), match.group(2), match.group(3), match.group(4))])
213                         return retval
214                 except:
215                         return []