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-2024 PhiloSoft Design"
9 __license__ = "GNU GPL"
11 __all__ = ['robot_base', 'get_error']
14 from base64 import b64encode
15 from urllib.parse import urlsplit, urljoin
20 from m_lib.md5wrapper import md5wrapper
21 from m_lib.net.www.util import parse_time
23 from bkmk_objects import Robot
24 from parse_html import parse_html
27 # Fake headers to pretend this is a real browser
28 _user_agent = "Mozilla/5.0 (X11; U; Linux 2.6 i686; en)"
29 " Gecko/20001221 Firefox/2.0.0"
30 _x_user_agent = "bookmarks_db (Python %d.%d.%d)" % sys.version_info[:3]
34 'Accept-Language': 'ru,en',
35 'Cache-Control': 'max-age=300',
36 'Connection': 'close',
38 'User-Agent': _user_agent,
39 'X-User-Agent': _x_user_agent,
54 if isinstance(e, str):
60 s.append("'%s'" % str(i).replace('\n', "\\n"))
61 return "(%s)" % ' '.join(s)
64 # Icon cache; maps URL to a tuple (content type, data)
65 # or None if there is no icon.
69 class robot_base(Robot):
72 def __init__(self, *args, **kw):
73 Robot.__init__(self, *args, **kw)
74 socket.setdefaulttimeout(int(self.timeout))
76 def check_url(self, bookmark):
78 self.start = int(time.time())
81 split_results = urlsplit(bookmark.href)
82 url_type, netloc, url_path, query, url_tag = split_results
83 url_host = split_results.hostname
85 url = "%s://%s%s" % (url_type, url_host, url_path)
86 error, redirect_code, redirect_to, headers, content = \
87 self.get(bookmark, url, True)
90 bookmark.error = error
94 self.set_redirect(bookmark, redirect_code, redirect_to)
102 size = headers["Content-Length"]
107 last_modified = headers["Last-Modified"]
112 last_modified = parse_time(last_modified)
114 if not size: # Could be None from headers
118 last_modified = str(int(last_modified))
120 last_modified = bookmark.last_visit
123 bookmark.last_modified = last_modified
128 content_type = headers["Content-Type"]
129 self.log(" Content-Type : %s" % content_type)
130 if content_type is None:
131 if b'html' in content.lower():
132 content_type = 'text/html'
134 content_type = 'text/plain'
135 self.log(" Set Content-Type to: %s"
138 # extract charset from
139 # "text/html; charset=UTF-8, foo; bar"
140 content_type, charset = content_type.split(';', 1)
141 content_type = content_type.strip()
142 charset = charset.split('=')[1].strip().split(',')[0]
143 self.log(" HTTP charset : %s" % charset)
144 except (ValueError, IndexError):
146 self.log(" no charset in Content-Type header")
148 for ctype in ("text/html", "application/xhtml+xml"):
149 if content_type.startswith(ctype):
152 content_stripped = content.strip()
153 if content_stripped and charset:
155 content_stripped = content_stripped.decode(
159 self.log(" unknown charset "
160 "in Content-Type header")
161 if content_stripped and is_html:
163 content_stripped, charset, self.log)
165 bookmark.charset = charset
166 elif parser and parser.meta_charset:
167 bookmark.charset = parser.meta_charset
169 bookmark.real_title = parser.title
174 icon = "/favicon.ico"
176 "%s://%s%s" % (url_type, url_host, url_path), icon)
177 self.log(" looking for icon at: %s" % icon_url)
178 if icon_url in icons:
180 bookmark.icon_href = icon_url
181 content_type, bookmark.icon = icons[icon_url]
182 self.log(" cached icon : %s"
185 self.log(" cached icon : no icon")
186 elif icon_url.startswith('data:'):
187 content_type, icon_data = \
188 icon_url[len('data:'):].split(',', 1)
189 bookmark.icon_href = bookmark.icon = icon_url
190 self.log(" got data icon : %s" % content_type)
191 icons[icon_url] = (content_type, icon_url)
196 error, icon_redirect_code, \
197 icon_redirect_to, icon_headers, \
199 self.get(bookmark, _icon_url)
200 if icon_redirect_code:
201 _icon_url = icon_redirect_to
202 self.log(" redirect to : %s"
205 if icon_data is None:
206 raise IOError("No icon")
209 raise IOError("Too many redirects")
211 etype, emsg, _ = sys.exc_info()
212 self.log(" no icon : %s %s"
214 etype = emsg = _ = None
215 icons[icon_url] = None
217 content_type = icon_headers["Content-Type"]
218 if content_type and (
219 content_type.startswith("application/")
220 or content_type.startswith("image/")
221 or content_type.startswith("text/plain")
223 bookmark.icon_href = icon_url
224 self.log(" got icon : %s"
227 content_type.startswith("application/")
228 or content_type.startswith(
231 self.log(" non-image content type,"
233 content_type = 'image/x-icon'
234 if not isinstance(icon_data, bytes):
235 icon_data = icon_data.encode('latin1')
236 bookmark.icon = "data:%s;base64,%s" \
237 % (content_type, b64encode(icon_data))
238 icons[icon_url] = (content_type,
242 self.log(" no icon : "
243 "bad content type '%s'"
246 icons[icon_url] = None
247 if parser and parser.refresh:
248 refresh = parser.refresh
250 url = refresh.split('=', 1)[1]
254 timeout = float(refresh.split(';')[0])
255 except (IndexError, ValueError):
256 self.set_redirect(bookmark, "html",
257 "Bad redirect to %s (%s)"
262 timeout = int(refresh.split(';')[0])
265 self.set_redirect(bookmark, "html",
270 bookmark.charset = charset
272 if not content_stripped:
273 self.log(" empty response, no content")
275 self.log(" not html")
276 except KeyError as key:
277 self.log(" no header: %s" % key)
280 if url_type == "ftp": # Pass welcome message through MD5
281 ftp_welcome = self.get_ftp_welcome()
282 if not isinstance(ftp_welcome, bytes):
283 ftp_welcome = ftp_welcome.encode(charset or 'utf-8')
284 md5.update(ftp_welcome)
286 if isinstance(content, bytes):
289 md5.update(content.encode(charset or 'utf-8'))
290 bookmark.md5 = str(md5)
293 bookmark.error = "Unexpected EOF (FTP server closed connection)"
294 self.log(' EOF: %s' % bookmark.error)
296 except KeyboardInterrupt:
297 self.log("Keyboard interrupt (^C)")
300 except socket.error as e:
301 bookmark.error = get_error(e)
302 self.log(bookmark.error)
306 traceback.print_exc()
307 bookmark.error = "Exception!"
308 self.log(' Exception: %s' % bookmark.error)
311 self.finish_check_url(bookmark)
316 def set_redirect(self, bookmark, errcode, newurl):
317 bookmark.moved = moved = "(%s) to %s" % (reloc_dict[errcode], newurl)
319 moved.encode('ascii')
320 except UnicodeEncodeError:
322 moved = moved.encode(bookmark.charset)
323 except (LookupError, TypeError, UnicodeEncodeError):
324 moved = moved.encode('utf-8')
325 self.log(' Moved: %s' % moved)
327 def finish_check_url(self, bookmark):
329 bookmark.last_tested = str(start)
330 now = int(time.time())
331 bookmark.test_time = str(now - start)