Added a dummy address book backend
[gc-dialer] / src / browser_emu.py
1 """
2 @author:          Laszlo Nagy
3 @copyright:   (c) 2005 by Szoftver Messias Bt.
4 @licence:        BSD style
5
6 Objects of the MozillaEmulator class can emulate a browser that is capable of:
7
8         - cookie management
9         - caching
10         - configurable user agent string
11         - GET and POST
12         - multipart POST (send files)
13         - receive content into file
14         - progress indicator
15
16 I have seen many requests on the python mailing list about how to emulate a browser. I'm using this class for years now, without any problems. This is how you can use it:
17
18         1. Use firefox
19         2. Install and open the livehttpheaders plugin
20         3. Use the website manually with firefox
21         4. Check the GET and POST requests in the livehttpheaders capture window
22         5. Create an instance of the above class and send the same GET and POST requests to the server.
23
24 Optional steps:
25
26         - For testing, use a MozillaCacher instance - this will cache all pages and make testing quicker
27         - You can change user agent string in the build_opened method
28         - The "encode_multipart_formdata" function can be used alone to create POST data from a list of field values and files
29
30 TODO:
31
32 - should have a method to save/load cookies
33 """
34
35 import os
36 import urllib
37 import urllib2
38 import cookielib
39 import warnings
40
41
42 class MozillaEmulator(object):
43
44         def __init__(self, cacher=None, trycount=0):
45                 """Create a new MozillaEmulator object.
46
47                 @param cacher: A dictionary like object, that can cache search results on a storage device.
48                         You can use a simple dictionary here, but it is not recommended.
49                         You can also put None here to disable caching completely.
50                 @param trycount: The download() method will retry the operation if it fails. You can specify -1 for infinite retrying.
51                          A value of 0 means no retrying. A value of 1 means one retry. etc."""
52                 if cacher is None:
53                         cacher = {}
54                 self.cacher = cacher
55                 self.cookies = cookielib.LWPCookieJar()
56                 self.debug = False
57                 self.trycount = trycount
58
59         def build_opener(self, url, postdata=None, extraheaders=None, forbid_redirect=False):
60                 if extraheaders is None:
61                         extraheaders = {}
62
63                 txheaders = {
64                         'Accept': 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png',
65                         'Accept-Language': 'en,en-us;q=0.5',
66                         'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
67                 }
68                 for key, value in extraheaders.iteritems():
69                         txheaders[key] = value
70                 req = urllib2.Request(url, postdata, txheaders)
71                 self.cookies.add_cookie_header(req)
72                 if forbid_redirect:
73                         redirector = HTTPNoRedirector()
74                 else:
75                         redirector = urllib2.HTTPRedirectHandler()
76
77                 http_handler = urllib2.HTTPHandler(debuglevel=self.debug)
78                 https_handler = urllib2.HTTPSHandler(debuglevel=self.debug)
79
80                 u = urllib2.build_opener(
81                         http_handler,
82                         https_handler,
83                         urllib2.HTTPCookieProcessor(self.cookies),
84                         redirector
85                 )
86                 u.addheaders = [(
87                         'User-Agent',
88                         'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.8) Gecko/20050511 Firefox/1.0.4'
89                 )]
90                 if not postdata is None:
91                         req.add_data(postdata)
92                 return (req, u)
93
94         def download(self, url, postdata=None, extraheaders=None, forbid_redirect=False,
95                         trycount=None, fd=None, onprogress=None, only_head=False):
96                 """Download an URL with GET or POST methods.
97
98                 @param postdata: It can be a string that will be POST-ed to the URL.
99                         When None is given, the method will be GET instead.
100                 @param extraheaders: You can add/modify HTTP headers with a dict here.
101                 @param forbid_redirect: Set this flag if you do not want to handle
102                         HTTP 301 and 302 redirects.
103                 @param trycount: Specify the maximum number of retries here.
104                         0 means no retry on error. Using -1 means infinite retring.
105                         None means the default value (that is self.trycount).
106                 @param fd: You can pass a file descriptor here. In this case,
107                         the data will be written into the file. Please note that
108                         when you save the raw data into a file then it won't be cached.
109                 @param onprogress: A function that has two parameters:
110                         the size of the resource and the downloaded size. This will be
111                         called for each 1KB chunk. (If the HTTP header does not contain
112                         the content-length field, then the size parameter will be zero!)
113                 @param only_head: Create the openerdirector and return it. In other
114                         words, this will not retrieve any content except HTTP headers.
115
116                 @return: The raw HTML page data, unless fd was specified. When fd
117                         was given, the return value is undefined.
118                 """
119                 warnings.warn("Performing download of %s" % url, UserWarning, 2)
120
121                 if extraheaders is None:
122                         extraheaders = {}
123                 if trycount is None:
124                         trycount = self.trycount
125                 cnt = 0
126                 while True:
127                         try:
128                                 req, u = self.build_opener(url, postdata, extraheaders, forbid_redirect)
129                                 openerdirector = u.open(req)
130                                 if self.debug:
131                                         print req.get_method(), url
132                                         print openerdirector.code, openerdirector.msg
133                                         print openerdirector.headers
134                                 self.cookies.extract_cookies(openerdirector, req)
135                                 if only_head:
136                                         return openerdirector
137                                 return openerdirector.read()
138                         except urllib2.URLError:
139                                 cnt += 1
140                                 if (trycount > -1) and (trycount < cnt):
141                                         raise
142                                 # Retry :-)
143                                 if self.debug:
144                                         print "MozillaEmulator: urllib2.URLError, retryting ", cnt
145
146
147 class HTTPNoRedirector(urllib2.HTTPRedirectHandler):
148         """This is a custom http redirect handler that FORBIDS redirection."""
149
150         def http_error_302(self, req, fp, code, msg, headers):
151                 e = urllib2.HTTPError(req.get_full_url(), code, msg, headers, fp)
152                 if e.code in (301, 302):
153                         if 'location' in headers:
154                                 newurl = headers.getheaders('location')[0]
155                         elif 'uri' in headers:
156                                 newurl = headers.getheaders('uri')[0]
157                         e.newurl = newurl
158                 raise e