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-2023 PhiloSoft Design"
9 __license__ = "GNU GPL"
11 __all__ = ['robot_base', 'get_error']
14 from base64 import b64encode
19 from urlparse import urljoin
21 from m_lib.md5wrapper import md5wrapper
22 from m_lib.net.www.util import parse_time
24 from bkmk_objects import Robot
25 from parse_html import parse_html
38 if isinstance(e, str):
44 s.append("'%s'" % str(i).replace('\n', "\\n"))
45 return "(%s)" % ' '.join(s)
48 # Icon cache; maps URL to a tuple (content type, data)
49 # or None if there is no icon.
53 class robot_base(Robot):
56 def __init__(self, *args, **kw):
57 Robot.__init__(self, *args, **kw)
58 socket.setdefaulttimeout(int(self.timeout))
60 def check_url(self, bookmark):
62 self.start = int(time.time())
65 url_type, url_rest = urllib.splittype(bookmark.href)
66 url_host, url_path = urllib.splithost(url_rest)
67 url_path, url_tag = urllib.splittag(url_path) # noqa: E221
68 # multiple spaces before operator
70 url = "%s://%s%s" % (url_type, url_host, url_path)
71 error, redirect_code, redirect_to, headers, content = \
72 self.get(bookmark, url, True)
75 bookmark.error = error
79 self.set_redirect(bookmark, redirect_code, redirect_to)
87 size = headers["Content-Length"]
92 last_modified = headers["Last-Modified"]
97 last_modified = parse_time(last_modified)
102 last_modified = str(int(last_modified))
104 last_modified = bookmark.last_visit
107 bookmark.last_modified = last_modified
110 if url_type == "ftp": # Pass welcome message through MD5
111 md5.update(self.get_ftp_welcome())
114 bookmark.md5 = str(md5)
118 content_type = headers["Content-Type"]
119 self.log(" Content-Type: %s" % content_type)
121 # extract charset from
122 # "text/html; foo; charset=UTF-8, bar; baz;"
123 content_type, charset = content_type.split(';', 1)
124 content_type = content_type.strip()
125 charset = charset.split('=')[1].strip().split(',')[0]
126 self.log(" HTTP charset : %s" % charset)
127 except (ValueError, IndexError):
129 self.log(" no charset in Content-Type header")
130 for ctype in ("text/html", "application/xhtml+xml"):
131 if content_type.startswith(ctype):
137 parser = parse_html(content, charset, self.log)
139 bookmark.real_title = parser.title
144 icon = "/favicon.ico"
146 "%s://%s%s" % (url_type, url_host, url_path), icon)
147 self.log(" looking for icon at: %s" % icon_url)
148 if icon_url in icons:
150 bookmark.icon_href = icon_url
151 content_type, bookmark.icon = icons[icon_url]
152 self.log(" cached icon: %s" % content_type)
154 self.log(" cached icon: no icon")
159 error, icon_redirect_code, \
160 icon_redirect_to, icon_headers, \
162 self.get(bookmark, _icon_url)
163 if icon_redirect_code:
164 _icon_url = icon_redirect_to
165 self.log(" redirect to : %s"
168 if icon_data is None:
169 raise IOError("No icon")
172 raise IOError("Too many redirects")
174 etype, emsg, tb = sys.exc_info()
175 self.log(" no icon : %s %s"
177 etype = emsg = tb = None
178 icons[icon_url] = None
180 content_type = icon_headers["Content-Type"]
181 if content_type.startswith("application/") \
182 or content_type.startswith("image/") \
183 or content_type.startswith("text/plain"):
184 bookmark.icon_href = icon_url
185 self.log(" got icon : %s"
188 content_type.startswith("application/")
189 or content_type.startswith(
192 self.log(" non-image content type,"
194 content_type = 'image/x-icon'
195 bookmark.icon = "data:%s;base64,%s" \
196 % (content_type, b64encode(icon_data))
197 icons[icon_url] = (content_type,
201 self.log(" no icon :"
202 "bad content type '%s'"
205 icons[icon_url] = None
206 if parser and parser.refresh:
207 refresh = parser.refresh
209 url = refresh.split('=', 1)[1]
213 timeout = float(refresh.split(';')[0])
214 except (IndexError, ValueError):
215 self.set_redirect(bookmark, "html",
216 "Bad redirect to %s (%s)"
221 timeout = int(refresh.split(';')[0])
224 self.set_redirect(bookmark, "html",
229 except KeyError as key:
230 self.log(" no header: %s" % key)
233 bookmark.error = "Unexpected EOF (FTP server closed connection)"
234 self.log(' EOF: %s' % bookmark.error)
236 except KeyboardInterrupt:
237 self.log("Keyboard interrupt (^C)")
240 except socket.error as e:
241 bookmark.error = get_error(e)
242 self.log(bookmark.error)
246 traceback.print_exc()
247 bookmark.error = "Exception!"
248 self.log(' Exception: %s' % bookmark.error)
251 self.finish_check_url(bookmark)
256 def set_redirect(self, bookmark, errcode, newurl):
257 bookmark.moved = "(%s) to %s" % (reloc_dict[errcode], newurl)
258 self.log(' Moved: %s' % bookmark.moved)
260 def finish_check_url(self, bookmark):
262 bookmark.last_tested = str(start)
263 now = int(time.time())
264 bookmark.test_time = str(now - start)