1 """Simple, strightforward robot
3 This file is a part of Bookmarks database and Internet robot.
7 __author__ = "Oleg Broytman <phd@phdru.name>"
8 __copyright__ = "Copyright (C) 2000-2012 PhiloSoft Design"
9 __license__ = "GNU GPL"
11 __all__ = ['robot_simple', 'get_error']
16 from base64 import b64encode
17 from urlparse import urljoin
19 from m_lib.net.www.util import parse_time
20 from m_lib.md5wrapper import md5wrapper
22 from bkmk_objects import Robot
23 from parse_html import parse_html
26 class RedirectException(Exception):
34 def __init__(self, errcode, newurl):
35 Exception.__init__(self, "(%s) to %s" % (self.reloc_dict[errcode], newurl))
39 class MyURLopener(urllib.URLopener):
40 # Error 302 -- relocated (temporarily)
41 def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
42 if headers.has_key('location'):
43 newurl = headers['location']
44 elif headers.has_key('uri'):
45 newurl = headers['uri']
48 raise RedirectException(errcode, newurl)
50 # Error 301 -- also relocated (permanently)
51 http_error_301 = http_error_302
52 # Error 307 -- also relocated (temporary)
53 http_error_307 = http_error_302
55 # Error 401 -- authentication required
56 def http_error_401(self, url, fp, errcode, errmsg, headers, data=None):
57 raise IOError, ('http error', errcode, "Authentication required ", headers)
59 def http_error_default(self, url, fp, errcode, errmsg, headers):
63 raise IOError, ('http error', errcode, errmsg, headers)
66 urllib._urlopener = MyURLopener()
68 # Fake headers to pretend this is a real browser
69 _version = "Mozilla/5.0 (X11; U; Linux 2.6 i686; en) Gecko/20001221 Firefox/2.0.0"
70 urllib._urlopener.addheaders[0] = ('User-Agent', _version)
71 _version = "bookmarks_db (Python %d.%d.%d; urllib/%s)" % (
72 sys.version_info[0], sys.version_info[1], sys.version_info[2], urllib.__version__)
73 urllib._urlopener.addheader('X-User-Agent', _version)
74 urllib._urlopener.addheader('Referer', '')
76 urllib._urlopener.addheader('Connection', 'close')
77 urllib._urlopener.addheader('Accept', '*/*')
78 urllib._urlopener.addheader('Accept-Language', 'ru,en')
79 urllib._urlopener.addheader('Cache-Control', 'max-age=300')
83 if isinstance(msg, str):
89 s.append("'%s'" % str(i).replace('\n', "\\n"))
90 return "(%s)" % ' '.join(s)
93 urllib_ftpwrapper = urllib.ftpwrapper
96 class myftpwrapper(urllib_ftpwrapper):
97 def __init__(self, user, passwd, host, port, dirs):
98 urllib_ftpwrapper.__init__(self, user, passwd, host, port, dirs)
100 ftpcache_key = (user, host, port, '/'.join(dirs))
102 urllib.ftpwrapper = myftpwrapper
106 _welcome = urllib._urlopener.ftpcache[ftpcache_key].ftp.welcome
107 ftpcache_key = None # I am assuming there are no duplicate ftp URLs in db.
108 # If there are - ftpcache_key in prev line is invalid.
112 icons = {} # Icon cache; maps URL to a tuple (content type, data)
113 # or None if there is no icon.
115 class robot_simple(Robot):
116 def check_url(self, bookmark):
119 self.start = int(time.time())
122 url_type, url_rest = urllib.splittype(bookmark.href)
123 url_host, url_path = urllib.splithost(url_rest)
124 url_path, url_tag = urllib.splittag(url_path)
126 # Set fake referer to the root of the site
127 urllib._urlopener.addheaders[2] = ('Referer', "%s://%s%s" % (url_type, url_host, url_path))
129 if bookmark.charset: urllib._urlopener.addheader('Accept-Charset', bookmark.charset)
130 fname, headers = urllib.urlretrieve("%s://%s%s" % (url_type, url_host, url_path))
131 if bookmark.charset: del urllib._urlopener.addheaders[-1]
138 size = headers["Content-Length"]
143 last_modified = headers["Last-Modified"]
148 last_modified = parse_time(last_modified)
151 last_modified = str(int(last_modified))
153 last_modified = bookmark.last_visit
156 bookmark.last_modified = last_modified
159 if urllib._urlopener.type == "ftp": # Pass welcome message through MD5
160 md5.update(get_welcome())
163 bookmark.md5 = str(md5)
167 content_type = headers["Content-Type"]
168 self.log(" Content-Type: %s" % content_type)
170 # extract charset from "text/html; foo; charset=UTF-8, bar; baz;"
171 content_type, charset = content_type.split(';', 1)
172 content_type = content_type.strip()
173 charset = charset.split('=')[1].strip().split(',')[0]
174 self.log(" HTTP charset : %s" % charset)
175 except (ValueError, IndexError):
177 self.log(" no charset in Content-Type header")
178 for ctype in ("text/html", "application/xhtml+xml"):
179 if content_type.startswith(ctype):
185 parser = parse_html(fname, charset, self.log)
187 bookmark.real_title = parser.title
192 icon = "/favicon.ico"
193 icon = urljoin("%s://%s%s" % (url_type, url_host, url_path), icon)
194 self.log(" looking for icon at: %s" % icon)
197 bookmark.icon_href = icon
198 content_type, bookmark.icon = icons[icon]
199 self.log(" cached icon: %s" % content_type)
201 self.log(" cached icon: no icon")
207 icon_fname, headers = urllib.urlretrieve(_icon)
208 except RedirectException, e:
210 self.log(" redirect to : %s" % _icon)
214 raise IOError("Too many redirects")
216 etype, emsg, tb = sys.exc_info()
217 self.log(" no icon : %s %s" % (etype, emsg))
218 etype = emsg = tb = None
221 content_type = headers["Content-Type"]
222 if content_type.startswith("application/") \
223 or content_type.startswith("image/") \
224 or content_type.startswith("text/plain"):
225 icon_file = open(icon_fname, "rb")
226 icon_data = icon_file.read()
228 bookmark.icon_href = icon
229 self.log(" got icon : %s" % content_type)
230 if content_type.startswith("application/") \
231 or content_type.startswith("text/plain"):
232 self.log(" non-image content type, assume x-icon")
233 content_type = 'image/x-icon'
234 bookmark.icon = "data:%s;base64,%s" % (content_type, b64encode(icon_data))
235 icons[icon] = (content_type, bookmark.icon)
237 self.log(" no icon : bad content type '%s'" % content_type)
239 if parser and parser.refresh:
240 refresh = parser.refresh
242 url = refresh.split('=', 1)[1]
246 timeout = float(refresh.split(';')[0])
247 except (IndexError, ValueError):
248 raise RedirectException("html", "Bad redirect to %s (%s)" % (url, refresh))
251 timeout = int(refresh.split(';')[0])
254 raise RedirectException("html", "%s (%s sec)" % (url, timeout))
256 except KeyError, key:
257 self.log(" no header: %s" % key)
260 if (msg[0] == "http error") and (msg[1] == -1):
261 bookmark.no_error = "The server did not return any header - it is not an error, actually"
262 self.log(' no headers: %s' % bookmark.no_error)
264 bookmark.error = get_error(msg)
265 self.log(' Error: %s' % bookmark.error)
268 bookmark.error = "Unexpected EOF (FTP server closed connection)"
269 self.log(' EOF: %s' % bookmark.error)
271 except RedirectException, msg:
272 bookmark.moved = str(msg)
273 self.log(' Moved: %s' % bookmark.moved)
275 except KeyboardInterrupt:
276 self.log("Keyboard interrupt (^C)")
281 traceback.print_exc()
282 bookmark.error = "Exception!"
283 self.log(' Exception: %s' % bookmark.error)
286 self.finish_check_url(bookmark, fname)
291 def finish_check_url(self, bookmark, fname=None):
292 # Calculate these attributes even in case of an error
293 if fname and os.path.exists(fname):
294 size = str(os.path.getsize(fname))
300 bookmark.last_tested = str(start)
302 now = int(time.time())
303 bookmark.test_time = str(now - start)