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