2 Simple, strightforward robot
4 Written by Oleg Broytman. Copyright (C) 2000-2010 PhiloSoft Design.
9 from base64 import b64encode
10 from urlparse import urljoin
12 from m_lib.net.www.util import parse_time
13 from m_lib.md5wrapper import md5wrapper
15 from bkmk_objects import Robot
16 from parse_html import parse_html
19 class RedirectException(Exception):
25 def __init__(self, errcode, newurl):
26 Exception.__init__(self, "(%s) to %s" % (self.reloc_dict[errcode], newurl))
30 class MyURLopener(urllib.URLopener):
31 # Error 302 -- relocated (temporarily)
32 def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
33 if headers.has_key('location'):
34 newurl = headers['location']
35 elif headers.has_key('uri'):
36 newurl = headers['uri']
39 raise RedirectException(errcode, newurl)
41 # Error 301 -- also relocated (permanently)
42 http_error_301 = http_error_302
43 # Error 307 -- also relocated (temporary)
44 http_error_307 = http_error_302
46 # Error 401 -- authentication required
47 def http_error_401(self, url, fp, errcode, errmsg, headers, data=None):
48 raise IOError, ('http error', errcode, "Authentication required ", headers)
50 def http_error_default(self, url, fp, errcode, errmsg, headers):
54 raise IOError, ('http error', errcode, errmsg, headers)
57 urllib._urlopener = MyURLopener()
59 # Fake headers to pretend this is a real browser
60 _version = "Mozilla/5.0 (X11; U; Linux 2.6 i686; en) Gecko/20001221 Firefox/2.0.0"
61 urllib._urlopener.addheaders[0] = ('User-Agent', _version)
62 _version = "bookmarks_db (Python %d.%d.%d; urllib/%s)" % (
63 sys.version_info[0], sys.version_info[1], sys.version_info[2], urllib.__version__)
64 urllib._urlopener.addheader('X-User-Agent', _version)
65 urllib._urlopener.addheader('Referer', '')
67 urllib._urlopener.addheader('Connection', 'close')
68 urllib._urlopener.addheader('Accept', '*/*')
69 urllib._urlopener.addheader('Accept-Language', 'ru,en')
70 urllib._urlopener.addheader('Cache-Control', 'max-age=300')
74 if isinstance(msg, str):
80 s.append("'%s'" % str(i).replace('\n', "\\n"))
81 return "(%s)" % ' '.join(s)
84 urllib_ftpwrapper = urllib.ftpwrapper
87 class myftpwrapper(urllib_ftpwrapper):
88 def __init__(self, user, passwd, host, port, dirs):
89 urllib_ftpwrapper.__init__(self, user, passwd, host, port, dirs)
91 ftpcache_key = (user, host, port, '/'.join(dirs))
93 urllib.ftpwrapper = myftpwrapper
97 _welcome = urllib._urlopener.ftpcache[ftpcache_key].ftp.welcome
98 ftpcache_key = None # I am assuming there are no duplicate ftp URLs in db.
99 # If there are - ftpcache_key in prev line is invalid.
103 icons = {} # Icon cache; maps URL to a tuple (content type, data)
104 # or None if there is no icon.
106 class robot_simple(Robot):
107 def check_url(self, bookmark):
108 if not self.tempfname:
109 self.tempfname = bookmark.tempfname
112 self.start = int(time.time())
115 url_type, url_rest = urllib.splittype(bookmark.href)
116 url_host, url_path = urllib.splithost(url_rest)
117 url_path, url_tag = urllib.splittag(url_path)
119 # Set fake referer to the root of the site
120 urllib._urlopener.addheaders[2] = ('Referer', "%s://%s%s" % (url_type, url_host, url_path))
122 if bookmark.charset: urllib._urlopener.addheader('Accept-Charset', bookmark.charset)
123 fname, headers = urllib.urlretrieve("%s://%s%s" % (url_type, url_host, url_path), self.tempfname)
124 if bookmark.charset: del urllib._urlopener.addheaders[-1]
131 size = headers["Content-Length"]
136 last_modified = headers["Last-Modified"]
141 last_modified = parse_time(last_modified)
144 last_modified = str(int(last_modified))
146 last_modified = bookmark.last_visit
149 bookmark.last_modified = last_modified
152 if urllib._urlopener.type == "ftp": # Pass welcome message through MD5
153 md5.update(get_welcome())
155 md5.md5file(self.tempfname)
156 bookmark.md5 = str(md5)
160 content_type = headers["Content-Type"]
161 self.log(" Content-Type: %s" % content_type)
163 # extract charset from "text/html; foo; charset=UTF-8, bar; baz;"
164 content_type, charset = content_type.split(';', 1)
165 content_type = content_type.strip()
166 charset = charset.split('=')[1].strip().split(',')[0]
167 self.log(" HTTP charset : %s" % charset)
168 except (ValueError, IndexError):
170 self.log(" no charset in Content-Type header")
171 for ctype in ("text/html", "application/xhtml+xml"):
172 if content_type.startswith(ctype):
178 parser = parse_html(fname, charset, self.log)
180 bookmark.real_title = parser.title
182 refresh = parser.refresh
184 url = refresh.split('=', 1)[1]
188 timeout = float(refresh.split(';')[0])
189 except (IndexError, ValueError):
190 raise RedirectException("html", "Bad redirect to %s (%s)" % (url, refresh))
193 timeout = int(refresh.split(';')[0])
196 raise RedirectException("html", "%s (%s sec)" % (url, timeout))
203 icon = "/favicon.ico"
204 icon = urljoin("%s://%s%s" % (url_type, url_host, url_path), icon)
205 self.log(" looking for icon at: %s" % icon)
208 bookmark.icon_href = icon
209 content_type, bookmark.icon = icons[icon]
210 self.log(" cached icon: %s" % content_type)
212 self.log(" cached icon: no icon")
218 fname, headers = urllib.urlretrieve(_icon)
219 except RedirectException, e:
221 self.log(" redirect to : %s" % _icon)
225 raise IOError("Too many redirects")
227 etype, emsg, tb = sys.exc_info()
228 self.log(" no icon : %s %s" % (etype, emsg))
234 content_type = headers["Content-Type"]
235 if content_type.startswith("image/"):
236 icon_file = open(fname, "rb")
237 icon_data = icon_file.read()
239 bookmark.icon_href = icon
240 bookmark.icon = "data:%s;base64,%s" % (content_type, b64encode(icon_data))
241 self.log(" got icon : %s" % content_type)
242 icons[icon] = (content_type, bookmark.icon)
244 self.log(" no icon : bad content type '%s'" % content_type)
248 except KeyError, key:
249 self.log(" no header: %s" % key)
252 if (msg[0] == "http error") and (msg[1] == -1):
253 bookmark.no_error = "The server did not return any header - it is not an error, actually"
254 self.log(bookmark.no_error)
256 bookmark.error = get_error(msg)
257 self.log(bookmark.error)
260 bookmark.error = "Unexpected EOF (FTP server closed connection)"
261 self.log(bookmark.error)
263 except RedirectException, msg:
264 bookmark.moved = str(msg)
265 self.log(bookmark.moved)
267 except KeyboardInterrupt:
268 self.log("Keyboard interrupt (^C)")
273 traceback.print_exc()
274 bookmark.error = "Exception!"
275 self.log(bookmark.error)
278 self.finish_check_url(bookmark)
284 def finish_check_url(self, bookmark):
285 # Calculate these attributes even in case of an error
286 if os.path.exists(self.tempfname):
287 size = str(os.path.getsize(self.tempfname))
293 bookmark.last_tested = str(start)
295 now = int(time.time())
296 bookmark.test_time = str(now - start)