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