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, urljoin
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
42 if isinstance(e, str):
48 s.append("'%s'" % str(i).replace('\n', "\\n"))
49 return "(%s)" % ' '.join(s)
52 # Icon cache; maps URL to a tuple (content type, data)
53 # or None if there is no icon.
57 class robot_base(Robot):
60 def __init__(self, *args, **kw):
61 Robot.__init__(self, *args, **kw)
62 socket.setdefaulttimeout(int(self.timeout))
64 def check_url(self, bookmark):
66 self.start = int(time.time())
69 url_type, url_rest = splittype(bookmark.href)
70 url_host, url_path = splithost(url_rest)
71 url_path, url_tag = splittag(url_path) # noqa: E221
72 # multiple spaces before operator
74 url = "%s://%s%s" % (url_type, url_host, url_path)
75 error, redirect_code, redirect_to, headers, content = \
76 self.get(bookmark, url, True)
79 bookmark.error = error
83 self.set_redirect(bookmark, redirect_code, redirect_to)
91 size = headers["Content-Length"]
96 last_modified = headers["Last-Modified"]
101 last_modified = parse_time(last_modified)
103 if not size: # Could be None from headers
107 last_modified = str(int(last_modified))
109 last_modified = bookmark.last_visit
112 bookmark.last_modified = last_modified
115 if url_type == "ftp": # Pass welcome message through MD5
116 ftp_welcome = self.get_ftp_welcome()
117 if not isinstance(ftp_welcome, bytes):
118 ftp_welcome = ftp_welcome.encode('utf-8')
119 md5.update(ftp_welcome)
121 if isinstance(content, bytes):
124 md5.update(content.encode('utf-8'))
125 bookmark.md5 = str(md5)
129 content_type = headers["Content-Type"]
130 self.log(" Content-Type : %s" % content_type)
131 if content_type is None:
132 if 'html' in content.lower():
133 content_type = 'text/html'
135 content_type = 'text/plain'
136 self.log(" Set Content-Type to: %s"
139 # extract charset from
140 # "text/html; foo; charset=UTF-8, bar; baz;"
141 content_type, charset = content_type.split(';', 1)
142 content_type = content_type.strip()
143 charset = charset.split('=')[1].strip().split(',')[0]
144 self.log(" HTTP charset : %s" % charset)
145 except (ValueError, IndexError):
147 self.log(" no charset in Content-Type header")
149 for ctype in ("text/html", "application/xhtml+xml"):
150 if content_type.startswith(ctype):
153 content_stripped = content.strip()
154 if content_stripped and is_html:
155 parser = parse_html(content_stripped, charset, self.log)
157 bookmark.charset = charset
158 elif parser and parser.meta_charset:
159 bookmark.charset = parser.meta_charset
161 bookmark.real_title = parser.title
166 icon = "/favicon.ico"
168 "%s://%s%s" % (url_type, url_host, url_path), icon)
169 self.log(" looking for icon at: %s" % icon_url)
170 if icon_url in icons:
172 bookmark.icon_href = icon_url
173 content_type, bookmark.icon = icons[icon_url]
174 self.log(" cached icon: %s" % content_type)
176 self.log(" cached icon: no icon")
181 error, icon_redirect_code, \
182 icon_redirect_to, icon_headers, \
184 self.get(bookmark, _icon_url)
185 if icon_redirect_code:
186 _icon_url = icon_redirect_to
187 self.log(" redirect to : %s"
190 if icon_data is None:
191 raise IOError("No icon")
194 raise IOError("Too many redirects")
196 etype, emsg, _ = sys.exc_info()
197 self.log(" no icon : %s %s"
199 etype = emsg = _ = None
200 icons[icon_url] = None
202 content_type = icon_headers["Content-Type"]
203 if content_type and (
204 content_type.startswith("application/")
205 or content_type.startswith("image/")
206 or content_type.startswith("text/plain")
208 bookmark.icon_href = icon_url
209 self.log(" got icon : %s"
212 content_type.startswith("application/")
213 or content_type.startswith(
216 self.log(" non-image content type,"
218 content_type = 'image/x-icon'
219 if not isinstance(icon_data, bytes):
220 icon_data = icon_data.encode('utf-8')
221 bookmark.icon = "data:%s;base64,%s" \
222 % (content_type, b64encode(icon_data))
223 icons[icon_url] = (content_type,
227 self.log(" no icon :"
228 "bad content type '%s'"
231 icons[icon_url] = None
232 if parser and parser.refresh:
233 refresh = parser.refresh
235 url = refresh.split('=', 1)[1]
239 timeout = float(refresh.split(';')[0])
240 except (IndexError, ValueError):
241 self.set_redirect(bookmark, "html",
242 "Bad redirect to %s (%s)"
247 timeout = int(refresh.split(';')[0])
250 self.set_redirect(bookmark, "html",
255 if not content_stripped:
256 self.log(" empty response, no content")
258 self.log(" not html")
259 except KeyError as key:
260 self.log(" no header: %s" % key)
263 bookmark.error = "Unexpected EOF (FTP server closed connection)"
264 self.log(' EOF: %s' % bookmark.error)
266 except KeyboardInterrupt:
267 self.log("Keyboard interrupt (^C)")
270 except socket.error as e:
271 bookmark.error = get_error(e)
272 self.log(bookmark.error)
276 traceback.print_exc()
277 bookmark.error = "Exception!"
278 self.log(' Exception: %s' % bookmark.error)
281 self.finish_check_url(bookmark)
286 def set_redirect(self, bookmark, errcode, newurl):
287 bookmark.moved = moved = "(%s) to %s" % (reloc_dict[errcode], newurl)
289 moved.encode('ascii')
290 except UnicodeEncodeError:
292 moved = moved.encode(bookmark.charset)
293 except (LookupError, TypeError, UnicodeEncodeError):
294 moved = moved.encode('utf-8')
295 self.log(' Moved: %s' % moved)
297 def finish_check_url(self, bookmark):
299 bookmark.last_tested = str(start)
300 now = int(time.time())
301 bookmark.test_time = str(now - start)