]> git.phdru.name Git - bookmarks_db.git/blob - Robots/bkmk_robot_base.py
c5afd3fdc0aef90c1db8f69551e64c37e7c70882
[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                     pass
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
103             if not size:  # Could be None from headers
104                 size = len(content)
105
106             if last_modified:
107                 last_modified = str(int(last_modified))
108             else:
109                 last_modified = bookmark.last_visit
110
111             bookmark.size = size
112             bookmark.last_modified = last_modified
113
114             charset = None
115             if headers:
116                 try:
117                     content_type = headers["Content-Type"]
118                     self.log("   Content-Type   : %s" % content_type)
119                     if content_type is None:
120                         if b'html' in content.lower():
121                             content_type = 'text/html'
122                         else:
123                             content_type = 'text/plain'
124                         self.log("   Set Content-Type to: %s"
125                                  % content_type)
126                     try:
127                         # extract charset from
128                         # "text/html; charset=UTF-8, foo; bar"
129                         content_type, charset = content_type.split(';', 1)
130                         content_type = content_type.strip()
131                         charset = charset.split('=')[1].strip().split(',')[0]
132                         self.log("   HTTP charset   : %s" % charset)
133                     except (ValueError, IndexError):
134                         charset = None
135                         self.log("   no charset in Content-Type header")
136                     is_html = False
137                     for ctype in ("text/html", "application/xhtml+xml"):
138                         if content_type.startswith(ctype):
139                             is_html = True
140                             break
141                     content_stripped = content.strip()
142                     if content_stripped and charset:
143                         content_stripped = content_stripped.decode(
144                             charset, 'replace')
145                     if content_stripped and is_html:
146                         parser = parse_html(
147                             content_stripped, charset, self.log)
148                         if charset:
149                             bookmark.charset = charset
150                         elif parser and parser.meta_charset:
151                             bookmark.charset = parser.meta_charset
152                         if parser:
153                             bookmark.real_title = parser.title
154                             icon = parser.icon
155                         else:
156                             icon = None
157                         if not icon:
158                             icon = "/favicon.ico"
159                         icon_url = urljoin(
160                             "%s://%s%s" % (url_type, url_host, url_path), icon)
161                         self.log("   looking for icon at: %s" % icon_url)
162                         if icon_url in icons:
163                             if icons[icon_url]:
164                                 bookmark.icon_href = icon_url
165                                 content_type, bookmark.icon = icons[icon_url]
166                                 self.log("   cached icon: %s" % content_type)
167                             else:
168                                 self.log("   cached icon: no icon")
169                         else:
170                             try:
171                                 _icon_url = icon_url
172                                 for i in range(8):
173                                     error, icon_redirect_code, \
174                                         icon_redirect_to, icon_headers, \
175                                         icon_data = \
176                                         self.get(bookmark, _icon_url)
177                                     if icon_redirect_code:
178                                         _icon_url = icon_redirect_to
179                                         self.log("   redirect to : %s"
180                                                  % _icon_url)
181                                     else:
182                                         if icon_data is None:
183                                             raise IOError("No icon")
184                                         break
185                                 else:
186                                     raise IOError("Too many redirects")
187                             except:
188                                 etype, emsg, _ = sys.exc_info()
189                                 self.log("   no icon        : %s %s"
190                                          % (etype, emsg))
191                                 etype = emsg = _ = None
192                                 icons[icon_url] = None
193                             else:
194                                 content_type = icon_headers["Content-Type"]
195                                 if content_type and (
196                                     content_type.startswith("application/")
197                                     or content_type.startswith("image/")
198                                     or content_type.startswith("text/plain")
199                                 ):
200                                     bookmark.icon_href = icon_url
201                                     self.log("   got icon       : %s"
202                                              % content_type)
203                                     if (
204                                         content_type.startswith("application/")
205                                         or content_type.startswith(
206                                             "text/plain")
207                                     ):
208                                         self.log("   non-image content type,"
209                                                  " assume x-icon")
210                                         content_type = 'image/x-icon'
211                                     if not isinstance(icon_data, bytes):
212                                         icon_data = icon_data.encode('latin1')
213                                     bookmark.icon = "data:%s;base64,%s" \
214                                         % (content_type, b64encode(icon_data))
215                                     icons[icon_url] = (content_type,
216                                                        bookmark.icon
217                                                        )
218                                 else:
219                                     self.log("   no icon        :"
220                                              "bad content type '%s'"
221                                              % content_type
222                                              )
223                                     icons[icon_url] = None
224                         if parser and parser.refresh:
225                             refresh = parser.refresh
226                             try:
227                                 url = refresh.split('=', 1)[1]
228                             except IndexError:
229                                 url = "self"
230                             try:
231                                 timeout = float(refresh.split(';')[0])
232                             except (IndexError, ValueError):
233                                 self.set_redirect(bookmark, "html",
234                                                   "Bad redirect to %s (%s)"
235                                                   % (url, refresh)
236                                                   )
237                             else:
238                                 try:
239                                     timeout = int(refresh.split(';')[0])
240                                 except ValueError:
241                                     pass  # float timeout
242                                 self.set_redirect(bookmark, "html",
243                                                   "%s (%s sec)"
244                                                   % (url, timeout)
245                                                   )
246                     elif charset:
247                         bookmark.charset = charset
248
249                     if not content_stripped:
250                         self.log("   empty response, no content")
251                     if not is_html:
252                         self.log("   not html")
253                 except KeyError as key:
254                     self.log("   no header: %s" % key)
255
256             md5 = md5wrapper()
257             if url_type == "ftp":  # Pass welcome message through MD5
258                 ftp_welcome = self.get_ftp_welcome()
259                 if not isinstance(ftp_welcome, bytes):
260                     ftp_welcome = ftp_welcome.encode(charset or 'utf-8')
261                 md5.update(ftp_welcome)
262
263             if isinstance(content, bytes):
264                 md5.update(content)
265             else:
266                 md5.update(content.encode(charset or 'utf-8'))
267             bookmark.md5 = str(md5)
268
269         except EOFError:
270             bookmark.error = "Unexpected EOF (FTP server closed connection)"
271             self.log('   EOF: %s' % bookmark.error)
272
273         except KeyboardInterrupt:
274             self.log("Keyboard interrupt (^C)")
275             return 0
276
277         except socket.error as e:
278             bookmark.error = get_error(e)
279             self.log(bookmark.error)
280
281         except:
282             import traceback
283             traceback.print_exc()
284             bookmark.error = "Exception!"
285             self.log('   Exception: %s' % bookmark.error)
286
287         finally:
288             self.finish_check_url(bookmark)
289
290         # Tested
291         return 1
292
293     def set_redirect(self, bookmark, errcode, newurl):
294         bookmark.moved = moved = "(%s) to %s" % (reloc_dict[errcode], newurl)
295         try:
296             moved.encode('ascii')
297         except UnicodeEncodeError:
298             try:
299                 moved = moved.encode(bookmark.charset)
300             except (LookupError, TypeError, UnicodeEncodeError):
301                 moved = moved.encode('utf-8')
302         self.log('   Moved: %s' % moved)
303
304     def finish_check_url(self, bookmark):
305         start = self.start
306         bookmark.last_tested = str(start)
307         now = int(time.time())
308         bookmark.test_time = str(now - start)