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):
33 def __init__(self, errcode, newurl):
34 Exception.__init__(self, "(%s) to %s" % (self.reloc_dict[errcode], newurl))
38 class MyURLopener(urllib.URLopener):
39 # Error 302 -- relocated (temporarily)
40 def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
41 if headers.has_key('location'):
42 newurl = headers['location']
43 elif headers.has_key('uri'):
44 newurl = headers['uri']
47 raise RedirectException(errcode, newurl)
49 # Error 301 -- also relocated (permanently)
50 http_error_301 = http_error_302
51 # Error 307 -- also relocated (temporary)
52 http_error_307 = http_error_302
54 # Error 401 -- authentication required
55 def http_error_401(self, url, fp, errcode, errmsg, headers, data=None):
56 raise IOError, ('http error', errcode, "Authentication required ", headers)
58 def http_error_default(self, url, fp, errcode, errmsg, headers):
62 raise IOError, ('http error', errcode, errmsg, headers)
65 urllib._urlopener = MyURLopener()
67 # Fake headers to pretend this is a real browser
68 _version = "Mozilla/5.0 (X11; U; Linux 2.6 i686; en) Gecko/20001221 Firefox/2.0.0"
69 urllib._urlopener.addheaders[0] = ('User-Agent', _version)
70 _version = "bookmarks_db (Python %d.%d.%d; urllib/%s)" % (
71 sys.version_info[0], sys.version_info[1], sys.version_info[2], urllib.__version__)
72 urllib._urlopener.addheader('X-User-Agent', _version)
73 urllib._urlopener.addheader('Referer', '')
75 urllib._urlopener.addheader('Connection', 'close')
76 urllib._urlopener.addheader('Accept', '*/*')
77 urllib._urlopener.addheader('Accept-Language', 'ru,en')
78 urllib._urlopener.addheader('Cache-Control', 'max-age=300')
82 if isinstance(msg, str):
88 s.append("'%s'" % str(i).replace('\n', "\\n"))
89 return "(%s)" % ' '.join(s)
92 urllib_ftpwrapper = urllib.ftpwrapper
95 class myftpwrapper(urllib_ftpwrapper):
96 def __init__(self, user, passwd, host, port, dirs):
97 urllib_ftpwrapper.__init__(self, user, passwd, host, port, dirs)
99 ftpcache_key = (user, host, port, '/'.join(dirs))
101 urllib.ftpwrapper = myftpwrapper
105 _welcome = urllib._urlopener.ftpcache[ftpcache_key].ftp.welcome
106 ftpcache_key = None # I am assuming there are no duplicate ftp URLs in db.
107 # If there are - ftpcache_key in prev line is invalid.
111 icons = {} # Icon cache; maps URL to a tuple (content type, data)
112 # or None if there is no icon.
114 class robot_simple(Robot):
115 def check_url(self, bookmark):
118 self.start = int(time.time())
121 url_type, url_rest = urllib.splittype(bookmark.href)
122 url_host, url_path = urllib.splithost(url_rest)
123 url_path, url_tag = urllib.splittag(url_path)
125 # Set fake referer to the root of the site
126 urllib._urlopener.addheaders[2] = ('Referer', "%s://%s%s" % (url_type, url_host, url_path))
128 if bookmark.charset: urllib._urlopener.addheader('Accept-Charset', bookmark.charset)
129 fname, headers = urllib.urlretrieve("%s://%s%s" % (url_type, url_host, url_path))
130 if bookmark.charset: del urllib._urlopener.addheaders[-1]
137 size = headers["Content-Length"]
142 last_modified = headers["Last-Modified"]
147 last_modified = parse_time(last_modified)
150 last_modified = str(int(last_modified))
152 last_modified = bookmark.last_visit
155 bookmark.last_modified = last_modified
158 if urllib._urlopener.type == "ftp": # Pass welcome message through MD5
159 md5.update(get_welcome())
162 bookmark.md5 = str(md5)
166 content_type = headers["Content-Type"]
167 self.log(" Content-Type: %s" % content_type)
169 # extract charset from "text/html; foo; charset=UTF-8, bar; baz;"
170 content_type, charset = content_type.split(';', 1)
171 content_type = content_type.strip()
172 charset = charset.split('=')[1].strip().split(',')[0]
173 self.log(" HTTP charset : %s" % charset)
174 except (ValueError, IndexError):
176 self.log(" no charset in Content-Type header")
177 for ctype in ("text/html", "application/xhtml+xml"):
178 if content_type.startswith(ctype):
184 parser = parse_html(fname, charset, self.log)
186 bookmark.real_title = parser.title
191 icon = "/favicon.ico"
192 icon = urljoin("%s://%s%s" % (url_type, url_host, url_path), icon)
193 self.log(" looking for icon at: %s" % icon)
196 bookmark.icon_href = icon
197 content_type, bookmark.icon = icons[icon]
198 self.log(" cached icon: %s" % content_type)
200 self.log(" cached icon: no icon")
206 icon_fname, headers = urllib.urlretrieve(_icon)
207 except RedirectException, e:
209 self.log(" redirect to : %s" % _icon)
213 raise IOError("Too many redirects")
215 etype, emsg, tb = sys.exc_info()
216 self.log(" no icon : %s %s" % (etype, emsg))
217 etype = emsg = tb = None
220 content_type = headers["Content-Type"]
221 if content_type.startswith("application/") \
222 or content_type.startswith("image/") \
223 or content_type.startswith("text/plain"):
224 icon_file = open(icon_fname, "rb")
225 icon_data = icon_file.read()
227 bookmark.icon_href = icon
228 self.log(" got icon : %s" % content_type)
229 if content_type.startswith("application/") \
230 or content_type.startswith("text/plain"):
231 self.log(" non-image content type, assume x-icon")
232 content_type = 'image/x-icon'
233 bookmark.icon = "data:%s;base64,%s" % (content_type, b64encode(icon_data))
234 icons[icon] = (content_type, bookmark.icon)
236 self.log(" no icon : bad content type '%s'" % content_type)
238 if parser and parser.refresh:
239 refresh = parser.refresh
241 url = refresh.split('=', 1)[1]
245 timeout = float(refresh.split(';')[0])
246 except (IndexError, ValueError):
247 raise RedirectException("html", "Bad redirect to %s (%s)" % (url, refresh))
250 timeout = int(refresh.split(';')[0])
253 raise RedirectException("html", "%s (%s sec)" % (url, timeout))
255 except KeyError, key:
256 self.log(" no header: %s" % key)
259 if (msg[0] == "http error") and (msg[1] == -1):
260 bookmark.no_error = "The server did not return any header - it is not an error, actually"
261 self.log(' no headers: %s' % bookmark.no_error)
263 bookmark.error = get_error(msg)
264 self.log(' Error: %s' % bookmark.error)
267 bookmark.error = "Unexpected EOF (FTP server closed connection)"
268 self.log(' EOF: %s' % bookmark.error)
270 except RedirectException, msg:
271 bookmark.moved = str(msg)
272 self.log(' Moved: %s' % bookmark.moved)
274 except KeyboardInterrupt:
275 self.log("Keyboard interrupt (^C)")
280 traceback.print_exc()
281 bookmark.error = "Exception!"
282 self.log(' Exception: %s' % bookmark.error)
285 self.finish_check_url(bookmark, fname)
290 def finish_check_url(self, bookmark, fname=None):
291 # Calculate these attributes even in case of an error
292 if fname and os.path.exists(fname):
293 size = str(os.path.getsize(fname))
299 bookmark.last_tested = str(start)
301 now = int(time.time())
302 bookmark.test_time = str(now - start)