]> git.phdru.name Git - bookmarks_db.git/blob - Robots/bkmk_robot_base.py
Fix(robots): Store charset
[bookmarks_db.git] / Robots / bkmk_robot_base.py
1 """Base class for robots
2
3 This file is a part of Bookmarks database and Internet robot.
4
5 """
6
7 __author__ = "Oleg Broytman <phd@phdru.name>"
8 __copyright__ = "Copyright (C) 2000-2023 PhiloSoft Design"
9 __license__ = "GNU GPL"
10
11 __all__ = ['robot_base', 'get_error']
12
13
14 from base64 import b64encode
15 import sys
16 import socket
17 import time
18 try:
19     from urllib.parse import splittype, splithost, splittag, urljoin
20 except ImportError:
21     from urllib import splittype, splithost, splittag
22     from urlparse import urljoin
23
24 from m_lib.md5wrapper import md5wrapper
25 from m_lib.net.www.util import parse_time
26
27 from bkmk_objects import Robot
28 from parse_html import parse_html
29
30
31 reloc_dict = {
32   301: "perm1.",
33   302: "temp2.",
34   303: "temp3.",
35   307: "temp7.",
36   308: "temp8.",
37   "html": "html"
38 }
39
40
41 def get_error(e):
42     if isinstance(e, str):
43         return e
44
45     else:
46         s = []
47         for i in e:
48             s.append("'%s'" % str(i).replace('\n', "\\n"))
49         return "(%s)" % ' '.join(s)
50
51
52 # Icon cache; maps URL to a tuple (content type, data)
53 # or None if there is no icon.
54 icons = {}
55
56
57 class robot_base(Robot):
58     timeout = 60
59
60     def __init__(self, *args, **kw):
61         Robot.__init__(self, *args, **kw)
62         socket.setdefaulttimeout(int(self.timeout))
63
64     def check_url(self, bookmark):
65         try:
66             self.start = int(time.time())
67             bookmark.icon = None
68
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
73
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)
77
78             if error:
79                 bookmark.error = error
80                 return 1
81
82             if redirect_code:
83                 self.set_redirect(bookmark, redirect_code, redirect_to)
84                 return 1
85
86             size = 0
87             last_modified = None
88
89             if headers:
90                 try:
91                     size = headers["Content-Length"]
92                 except KeyError:
93                     size = len(content)
94
95                 try:
96                     last_modified = headers["Last-Modified"]
97                 except KeyError:
98                     pass
99
100                 if last_modified:
101                     last_modified = parse_time(last_modified)
102             else:
103                 size = len(content)
104
105             if last_modified:
106                 last_modified = str(int(last_modified))
107             else:
108                 last_modified = bookmark.last_visit
109
110             bookmark.size = size
111             bookmark.last_modified = last_modified
112
113             md5 = md5wrapper()
114             if url_type == "ftp":  # Pass welcome message through MD5
115                 ftp_welcome = self.get_ftp_welcome()
116                 if not isinstance(ftp_welcome, bytes):
117                     ftp_welcome = ftp_welcome.encode('utf-8')
118                 md5.update(ftp_welcome)
119
120             if isinstance(content, bytes):
121                 md5.update(content)
122             else:
123                 md5.update(content.encode('utf-8'))
124             bookmark.md5 = str(md5)
125
126             if headers:
127                 try:
128                     content_type = headers["Content-Type"]
129                     self.log("   Content-Type   : %s" % content_type)
130                     if content_type is None:
131                         if 'html' in content.lower():
132                             content_type = 'text/html'
133                         else:
134                             content_type = 'text/plain'
135                         self.log("   Set Content-Type to: %s"
136                                  % content_type)
137                     try:
138                         # extract charset from
139                         # "text/html; foo; charset=UTF-8, bar; baz;"
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):
145                         charset = None
146                         self.log("   no charset in Content-Type header")
147                     is_html = False
148                     for ctype in ("text/html", "application/xhtml+xml"):
149                         if content_type.startswith(ctype):
150                             is_html = True
151                             break
152                     content_stripped = content.strip()
153                     if content_stripped and is_html:
154                         parser = parse_html(content_stripped, charset, self.log)
155                         if charset:
156                             bookmark.charset = charset
157                         elif parser and parser.meta_charset:
158                             bookmark.charset = parser.meta_charset
159                         if parser:
160                             bookmark.real_title = parser.title
161                             icon = parser.icon
162                         else:
163                             icon = None
164                         if not icon:
165                             icon = "/favicon.ico"
166                         icon_url = urljoin(
167                             "%s://%s%s" % (url_type, url_host, url_path), icon)
168                         self.log("   looking for icon at: %s" % icon_url)
169                         if icon_url in icons:
170                             if icons[icon_url]:
171                                 bookmark.icon_href = icon_url
172                                 content_type, bookmark.icon = icons[icon_url]
173                                 self.log("   cached icon: %s" % content_type)
174                             else:
175                                 self.log("   cached icon: no icon")
176                         else:
177                             try:
178                                 _icon_url = icon_url
179                                 for i in range(8):
180                                     error, icon_redirect_code, \
181                                         icon_redirect_to, icon_headers, \
182                                         icon_data = \
183                                         self.get(bookmark, _icon_url)
184                                     if icon_redirect_code:
185                                         _icon_url = icon_redirect_to
186                                         self.log("   redirect to : %s"
187                                                  % _icon_url)
188                                     else:
189                                         if icon_data is None:
190                                             raise IOError("No icon")
191                                         break
192                                 else:
193                                     raise IOError("Too many redirects")
194                             except:
195                                 etype, emsg, _ = sys.exc_info()
196                                 self.log("   no icon        : %s %s"
197                                          % (etype, emsg))
198                                 etype = emsg = _ = None
199                                 icons[icon_url] = None
200                             else:
201                                 content_type = icon_headers["Content-Type"]
202                                 if content_type and (
203                                     content_type.startswith("application/")
204                                     or content_type.startswith("image/")
205                                     or content_type.startswith("text/plain")
206                                 ):
207                                     bookmark.icon_href = icon_url
208                                     self.log("   got icon       : %s"
209                                              % content_type)
210                                     if (
211                                         content_type.startswith("application/")
212                                         or content_type.startswith(
213                                             "text/plain")
214                                     ):
215                                         self.log("   non-image content type,"
216                                                  " assume x-icon")
217                                         content_type = 'image/x-icon'
218                                     if not isinstance(icon_data, bytes):
219                                         icon_data = icon_data.encode('utf-8')
220                                     bookmark.icon = "data:%s;base64,%s" \
221                                         % (content_type, b64encode(icon_data))
222                                     icons[icon_url] = (content_type,
223                                                        bookmark.icon
224                                                        )
225                                 else:
226                                     self.log("   no icon        :"
227                                              "bad content type '%s'"
228                                              % content_type
229                                              )
230                                     icons[icon_url] = None
231                         if parser and parser.refresh:
232                             refresh = parser.refresh
233                             try:
234                                 url = refresh.split('=', 1)[1]
235                             except IndexError:
236                                 url = "self"
237                             try:
238                                 timeout = float(refresh.split(';')[0])
239                             except (IndexError, ValueError):
240                                 self.set_redirect(bookmark, "html",
241                                                   "Bad redirect to %s (%s)"
242                                                   % (url, refresh)
243                                                   )
244                             else:
245                                 try:
246                                     timeout = int(refresh.split(';')[0])
247                                 except ValueError:
248                                     pass  # float timeout
249                                 self.set_redirect(bookmark, "html",
250                                                   "%s (%s sec)"
251                                                   % (url, timeout)
252                                                   )
253
254                     if not content_stripped:
255                         self.log("   empty response, no content")
256                     if not is_html:
257                         self.log("   not html")
258                 except KeyError as key:
259                     self.log("   no header: %s" % key)
260
261         except EOFError:
262             bookmark.error = "Unexpected EOF (FTP server closed connection)"
263             self.log('   EOF: %s' % bookmark.error)
264
265         except KeyboardInterrupt:
266             self.log("Keyboard interrupt (^C)")
267             return 0
268
269         except socket.error as e:
270             bookmark.error = get_error(e)
271             self.log(bookmark.error)
272
273         except:
274             import traceback
275             traceback.print_exc()
276             bookmark.error = "Exception!"
277             self.log('   Exception: %s' % bookmark.error)
278
279         finally:
280             self.finish_check_url(bookmark)
281
282         # Tested
283         return 1
284
285     def set_redirect(self, bookmark, errcode, newurl):
286         bookmark.moved = moved = "(%s) to %s" % (reloc_dict[errcode], newurl)
287         try:
288             moved.encode('ascii')
289         except UnicodeEncodeError:
290             try:
291                 moved = moved.encode(bookmark.charset)
292             except (LookupError, TypeError, UnicodeEncodeError):
293                 moved = moved.encode('utf-8')
294         self.log('   Moved: %s' % moved)
295
296     def finish_check_url(self, bookmark):
297         start = self.start
298         bookmark.last_tested = str(start)
299         now = int(time.time())
300         bookmark.test_time = str(now - start)