1 """Base class for robots
3 This file is a part of Bookmarks database and Internet robot.
7 __author__ = "Oleg Broytman <phd@phdru.name>"
8 __copyright__ = "Copyright (C) 2000-2014 PhiloSoft Design"
9 __license__ = "GNU GPL"
11 __all__ = ['robot_base', '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
36 if isinstance(msg, str):
42 s.append("'%s'" % str(i).replace('\n', "\\n"))
43 return "(%s)" % ' '.join(s)
46 icons = {} # Icon cache; maps URL to a tuple (content type, data)
47 # or None if there is no icon.
49 class robot_base(Robot):
50 def check_url(self, bookmark):
52 self.start = int(time.time())
55 url_type, url_rest = urllib.splittype(bookmark.href)
56 url_host, url_path = urllib.splithost(url_rest)
57 url_path, url_tag = urllib.splittag(url_path)
59 url = "%s://%s%s" % (url_type, url_host, url_path)
60 error, redirect_code, redirect_to, headers, content = self.get(bookmark, url, True)
63 bookmark.error = error
67 self.set_redirect(bookmark, redirect_code, redirect_to)
75 size = headers["Content-Length"]
80 last_modified = headers["Last-Modified"]
85 last_modified = parse_time(last_modified)
90 last_modified = str(int(last_modified))
92 last_modified = bookmark.last_visit
95 bookmark.last_modified = last_modified
98 if urllib._urlopener.type == "ftp": # Pass welcome message through MD5
99 md5.update(self.get_ftp_welcome())
102 bookmark.md5 = str(md5)
106 content_type = headers["Content-Type"]
107 self.log(" Content-Type: %s" % content_type)
109 # extract charset from "text/html; foo; charset=UTF-8, bar; baz;"
110 content_type, charset = content_type.split(';', 1)
111 content_type = content_type.strip()
112 charset = charset.split('=')[1].strip().split(',')[0]
113 self.log(" HTTP charset : %s" % charset)
114 except (ValueError, IndexError):
116 self.log(" no charset in Content-Type header")
117 for ctype in ("text/html", "application/xhtml+xml"):
118 if content_type.startswith(ctype):
124 parser = parse_html(content, charset, self.log)
126 bookmark.real_title = parser.title
131 icon = "/favicon.ico"
132 icon_url = urljoin("%s://%s%s" % (url_type, url_host, url_path), icon)
133 self.log(" looking for icon at: %s" % icon_url)
134 if icon_url in icons:
136 bookmark.icon_href = icon_url
137 content_type, bookmark.icon = icons[icon_url]
138 self.log(" cached icon: %s" % content_type)
140 self.log(" cached icon: no icon")
145 error, icon_redirect_code, icon_redirect_to, \
146 icon_headers, icon_data = \
147 self.get(bookmark, _icon_url)
148 if icon_redirect_code:
149 _icon_url = icon_redirect_to
150 self.log(" redirect to : %s" % _icon_url)
152 if icon_data is None:
153 raise IOError("No icon")
156 raise IOError("Too many redirects")
158 etype, emsg, tb = sys.exc_info()
159 self.log(" no icon : %s %s" % (etype, emsg))
160 etype = emsg = tb = None
161 icons[icon_url] = None
163 content_type = icon_headers["Content-Type"]
164 if content_type.startswith("application/") \
165 or content_type.startswith("image/") \
166 or content_type.startswith("text/plain"):
167 bookmark.icon_href = icon_url
168 self.log(" got icon : %s" % content_type)
169 if content_type.startswith("application/") \
170 or content_type.startswith("text/plain"):
171 self.log(" non-image content type, assume x-icon")
172 content_type = 'image/x-icon'
173 bookmark.icon = "data:%s;base64,%s" % (content_type, b64encode(icon_data))
174 icons[icon_url] = (content_type, bookmark.icon)
176 self.log(" no icon : bad content type '%s'" % content_type)
177 icons[icon_url] = None
178 if parser and parser.refresh:
179 refresh = parser.refresh
181 url = refresh.split('=', 1)[1]
185 timeout = float(refresh.split(';')[0])
186 except (IndexError, ValueError):
187 self.set_redirect(bookmark, "html", "Bad redirect to %s (%s)" % (url, refresh))
190 timeout = int(refresh.split(';')[0])
193 self.set_redirect(bookmark, "html", "%s (%s sec)" % (url, timeout))
195 except KeyError, key:
196 self.log(" no header: %s" % key)
199 bookmark.error = "Unexpected EOF (FTP server closed connection)"
200 self.log(' EOF: %s' % bookmark.error)
202 except KeyboardInterrupt:
203 self.log("Keyboard interrupt (^C)")
208 traceback.print_exc()
209 bookmark.error = "Exception!"
210 self.log(' Exception: %s' % bookmark.error)
213 self.finish_check_url(bookmark)
218 def set_redirect(self, bookmark, errcode, newurl):
219 bookmark.moved = "(%s) to %s" % (reloc_dict[errcode], newurl)
220 self.log(' Moved: %s' % bookmark.moved)
222 def finish_check_url(self, bookmark):
224 bookmark.last_tested = str(start)
225 now = int(time.time())
226 bookmark.test_time = str(now - start)