]> git.phdru.name Git - bookmarks_db.git/blob - Robots/bkmk_robot_base.py
9a74cb4ad67e342f96ec087e99186bb2eb69c4d2
[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: "perm.",
33   302: "temp2.",
34   303: "temp3.",
35   307: "temp7.",
36   "html": "html"
37 }
38
39
40 def get_error(e):
41     if isinstance(e, str):
42         return e
43
44     else:
45         s = []
46         for i in e:
47             s.append("'%s'" % str(i).replace('\n', "\\n"))
48         return "(%s)" % ' '.join(s)
49
50
51 # Icon cache; maps URL to a tuple (content type, data)
52 # or None if there is no icon.
53 icons = {}
54
55
56 class robot_base(Robot):
57     timeout = 60
58
59     def __init__(self, *args, **kw):
60         Robot.__init__(self, *args, **kw)
61         socket.setdefaulttimeout(int(self.timeout))
62
63     def check_url(self, bookmark):
64         try:
65             self.start = int(time.time())
66             bookmark.icon = None
67
68             url_type, url_rest = splittype(bookmark.href)
69             url_host, url_path = splithost(url_rest)
70             url_path, url_tag  = splittag(url_path)  # noqa: E221
71             #                    multiple spaces before operator
72
73             url = "%s://%s%s" % (url_type, url_host, url_path)
74             error, redirect_code, redirect_to, headers, content = \
75                 self.get(bookmark, url, True)
76
77             if error:
78                 bookmark.error = error
79                 return 1
80
81             if redirect_code:
82                 self.set_redirect(bookmark, redirect_code, redirect_to)
83                 return 1
84
85             size = 0
86             last_modified = None
87
88             if headers:
89                 try:
90                     size = headers["Content-Length"]
91                 except KeyError:
92                     size = len(content)
93
94                 try:
95                     last_modified = headers["Last-Modified"]
96                 except KeyError:
97                     pass
98
99                 if last_modified:
100                     last_modified = parse_time(last_modified)
101             else:
102                 size = len(content)
103
104             if last_modified:
105                 last_modified = str(int(last_modified))
106             else:
107                 last_modified = bookmark.last_visit
108
109             bookmark.size = size
110             bookmark.last_modified = last_modified
111
112             md5 = md5wrapper()
113             if url_type == "ftp":  # Pass welcome message through MD5
114                 ftp_welcome = self.get_ftp_welcome()
115                 if not isinstance(ftp_welcome, bytes):
116                     ftp_welcome = ftp_welcome.encode('utf-8')
117                 md5.update(ftp_welcome)
118
119             if isinstance(content, bytes):
120                 md5.update(content)
121             else:
122                 md5.update(content.encode('utf-8'))
123             bookmark.md5 = str(md5)
124
125             if headers:
126                 try:
127                     content_type = headers["Content-Type"]
128                     self.log("   Content-Type: %s" % content_type)
129                     try:
130                         # extract charset from
131                         # "text/html; foo; charset=UTF-8, bar; baz;"
132                         content_type, charset = content_type.split(';', 1)
133                         content_type = content_type.strip()
134                         charset = charset.split('=')[1].strip().split(',')[0]
135                         self.log("   HTTP charset   : %s" % charset)
136                     except (ValueError, IndexError):
137                         charset = None
138                         self.log("   no charset in Content-Type header")
139                     for ctype in ("text/html", "application/xhtml+xml"):
140                         if content_type.startswith(ctype):
141                             html = True
142                             break
143                     else:
144                         html = False
145                     if html:
146                         parser = parse_html(content, charset, self.log)
147                         if parser:
148                             bookmark.real_title = parser.title
149                             icon = parser.icon
150                         else:
151                             icon = None
152                         if not icon:
153                             icon = "/favicon.ico"
154                         icon_url = urljoin(
155                             "%s://%s%s" % (url_type, url_host, url_path), icon)
156                         self.log("   looking for icon at: %s" % icon_url)
157                         if icon_url in icons:
158                             if icons[icon_url]:
159                                 bookmark.icon_href = icon_url
160                                 content_type, bookmark.icon = icons[icon_url]
161                                 self.log("   cached icon: %s" % content_type)
162                             else:
163                                 self.log("   cached icon: no icon")
164                         else:
165                             try:
166                                 _icon_url = icon_url
167                                 for i in range(8):
168                                     error, icon_redirect_code, \
169                                         icon_redirect_to, icon_headers, \
170                                         icon_data = \
171                                         self.get(bookmark, _icon_url)
172                                     if icon_redirect_code:
173                                         _icon_url = icon_redirect_to
174                                         self.log("   redirect to : %s"
175                                                  % _icon_url)
176                                     else:
177                                         if icon_data is None:
178                                             raise IOError("No icon")
179                                         break
180                                 else:
181                                     raise IOError("Too many redirects")
182                             except:
183                                 etype, emsg, _ = sys.exc_info()
184                                 self.log("   no icon        : %s %s"
185                                          % (etype, emsg))
186                                 etype = emsg = _ = None
187                                 icons[icon_url] = None
188                             else:
189                                 content_type = icon_headers["Content-Type"]
190                                 if content_type.startswith("application/") \
191                                    or content_type.startswith("image/") \
192                                    or content_type.startswith("text/plain"):
193                                     bookmark.icon_href = icon_url
194                                     self.log("   got icon       : %s"
195                                              % content_type)
196                                     if (
197                                         content_type.startswith("application/")
198                                         or content_type.startswith(
199                                             "text/plain")
200                                     ):
201                                         self.log("   non-image content type,"
202                                                  " assume x-icon")
203                                         content_type = 'image/x-icon'
204                                     if not isinstance(icon_data, bytes):
205                                         icon_data = icon_data.encode('utf-8')
206                                     bookmark.icon = "data:%s;base64,%s" \
207                                         % (content_type, b64encode(icon_data))
208                                     icons[icon_url] = (content_type,
209                                                        bookmark.icon
210                                                        )
211                                 else:
212                                     self.log("   no icon        :"
213                                              "bad content type '%s'"
214                                              % content_type
215                                              )
216                                     icons[icon_url] = None
217                         if parser and parser.refresh:
218                             refresh = parser.refresh
219                             try:
220                                 url = refresh.split('=', 1)[1]
221                             except IndexError:
222                                 url = "self"
223                             try:
224                                 timeout = float(refresh.split(';')[0])
225                             except (IndexError, ValueError):
226                                 self.set_redirect(bookmark, "html",
227                                                   "Bad redirect to %s (%s)"
228                                                   % (url, refresh)
229                                                   )
230                             else:
231                                 try:
232                                     timeout = int(refresh.split(';')[0])
233                                 except ValueError:
234                                     pass  # float timeout
235                                 self.set_redirect(bookmark, "html",
236                                                   "%s (%s sec)"
237                                                   % (url, timeout)
238                                                   )
239
240                 except KeyError as key:
241                     self.log("   no header: %s" % key)
242
243         except EOFError:
244             bookmark.error = "Unexpected EOF (FTP server closed connection)"
245             self.log('   EOF: %s' % bookmark.error)
246
247         except KeyboardInterrupt:
248             self.log("Keyboard interrupt (^C)")
249             return 0
250
251         except socket.error as e:
252             bookmark.error = get_error(e)
253             self.log(bookmark.error)
254
255         except:
256             import traceback
257             traceback.print_exc()
258             bookmark.error = "Exception!"
259             self.log('   Exception: %s' % bookmark.error)
260
261         finally:
262             self.finish_check_url(bookmark)
263
264         # Tested
265         return 1
266
267     def set_redirect(self, bookmark, errcode, newurl):
268         bookmark.moved = "(%s) to %s" % (reloc_dict[errcode], newurl)
269         self.log('   Moved: %s' % bookmark.moved)
270
271     def finish_check_url(self, bookmark):
272         start = self.start
273         bookmark.last_tested = str(start)
274         now = int(time.time())
275         bookmark.test_time = str(now - start)