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 urllib.parse import splittype, splithost, splittag
21 from urllib import splittype, splithost, splittag
22 from urlparse import urljoin
24 from m_lib.md5wrapper import md5wrapper
25 from m_lib.net.www.util import parse_time
27 from bkmk_objects import Robot
28 from parse_html import parse_html
41 if isinstance(e, str):
47 s.append("'%s'" % str(i).replace('\n', "\\n"))
48 return "(%s)" % ' '.join(s)
51 # Icon cache; maps URL to a tuple (content type, data)
52 # or None if there is no icon.
56 class robot_base(Robot):
59 def __init__(self, *args, **kw):
60 Robot.__init__(self, *args, **kw)
61 socket.setdefaulttimeout(int(self.timeout))
63 def check_url(self, bookmark):
65 self.start = int(time.time())
68 url_type, url_rest = splittype(bookmark.href)
69 url_host, url_path = splithost(url_rest)
70 url_path, url_tag = splittag(url_path) # noqa: E221
71 # multiple spaces before operator
73 url = "%s://%s%s" % (url_type, url_host, url_path)
74 error, redirect_code, redirect_to, headers, content = \
75 self.get(bookmark, url, True)
78 bookmark.error = error
82 self.set_redirect(bookmark, redirect_code, redirect_to)
90 size = headers["Content-Length"]
95 last_modified = headers["Last-Modified"]
100 last_modified = parse_time(last_modified)
105 last_modified = str(int(last_modified))
107 last_modified = bookmark.last_visit
110 bookmark.last_modified = last_modified
113 if url_type == "ftp": # Pass welcome message through MD5
114 md5.update(self.get_ftp_welcome())
117 bookmark.md5 = str(md5)
121 content_type = headers["Content-Type"]
122 self.log(" Content-Type: %s" % content_type)
124 # extract charset from
125 # "text/html; foo; charset=UTF-8, bar; baz;"
126 content_type, charset = content_type.split(';', 1)
127 content_type = content_type.strip()
128 charset = charset.split('=')[1].strip().split(',')[0]
129 self.log(" HTTP charset : %s" % charset)
130 except (ValueError, IndexError):
132 self.log(" no charset in Content-Type header")
133 for ctype in ("text/html", "application/xhtml+xml"):
134 if content_type.startswith(ctype):
140 parser = parse_html(content, charset, self.log)
142 bookmark.real_title = parser.title
147 icon = "/favicon.ico"
149 "%s://%s%s" % (url_type, url_host, url_path), icon)
150 self.log(" looking for icon at: %s" % icon_url)
151 if icon_url in icons:
153 bookmark.icon_href = icon_url
154 content_type, bookmark.icon = icons[icon_url]
155 self.log(" cached icon: %s" % content_type)
157 self.log(" cached icon: no icon")
162 error, icon_redirect_code, \
163 icon_redirect_to, icon_headers, \
165 self.get(bookmark, _icon_url)
166 if icon_redirect_code:
167 _icon_url = icon_redirect_to
168 self.log(" redirect to : %s"
171 if icon_data is None:
172 raise IOError("No icon")
175 raise IOError("Too many redirects")
177 etype, emsg, _ = sys.exc_info()
178 self.log(" no icon : %s %s"
180 etype = emsg = _ = None
181 icons[icon_url] = None
183 content_type = icon_headers["Content-Type"]
184 if content_type.startswith("application/") \
185 or content_type.startswith("image/") \
186 or content_type.startswith("text/plain"):
187 bookmark.icon_href = icon_url
188 self.log(" got icon : %s"
191 content_type.startswith("application/")
192 or content_type.startswith(
195 self.log(" non-image content type,"
197 content_type = 'image/x-icon'
198 bookmark.icon = "data:%s;base64,%s" \
199 % (content_type, b64encode(icon_data))
200 icons[icon_url] = (content_type,
204 self.log(" no icon :"
205 "bad content type '%s'"
208 icons[icon_url] = None
209 if parser and parser.refresh:
210 refresh = parser.refresh
212 url = refresh.split('=', 1)[1]
216 timeout = float(refresh.split(';')[0])
217 except (IndexError, ValueError):
218 self.set_redirect(bookmark, "html",
219 "Bad redirect to %s (%s)"
224 timeout = int(refresh.split(';')[0])
227 self.set_redirect(bookmark, "html",
232 except KeyError as key:
233 self.log(" no header: %s" % key)
236 bookmark.error = "Unexpected EOF (FTP server closed connection)"
237 self.log(' EOF: %s' % bookmark.error)
239 except KeyboardInterrupt:
240 self.log("Keyboard interrupt (^C)")
243 except socket.error as e:
244 bookmark.error = get_error(e)
245 self.log(bookmark.error)
249 traceback.print_exc()
250 bookmark.error = "Exception!"
251 self.log(' Exception: %s' % bookmark.error)
254 self.finish_check_url(bookmark)
259 def set_redirect(self, bookmark, errcode, newurl):
260 bookmark.moved = "(%s) to %s" % (reloc_dict[errcode], newurl)
261 self.log(' Moved: %s' % bookmark.moved)
263 def finish_check_url(self, bookmark):
265 bookmark.last_tested = str(start)
266 now = int(time.time())
267 bookmark.test_time = str(now - start)