]> git.phdru.name Git - bookmarks_db.git/blob - Robots/bkmk_robot_base.py
9c9d8c5823543bc442472274068da5acbf8417b0
[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 = self.get(bookmark, url, True)
72
73             if error:
74                 bookmark.error = error
75                 return 1
76
77             if redirect_code:
78                 self.set_redirect(bookmark, redirect_code, redirect_to)
79                 return 1
80
81             size = 0
82             last_modified = None
83
84             if headers:
85                 try:
86                     size = headers["Content-Length"]
87                 except KeyError:
88                     size = len(content)
89
90                 try:
91                     last_modified = headers["Last-Modified"]
92                 except KeyError:
93                     pass
94
95                 if last_modified:
96                     last_modified = parse_time(last_modified)
97             else:
98                 size = len(content)
99
100             if last_modified:
101                 last_modified = str(int(last_modified))
102             else:
103                 last_modified = bookmark.last_visit
104
105             bookmark.size = size
106             bookmark.last_modified = last_modified
107
108             md5 = md5wrapper()
109             if url_type == "ftp":  # Pass welcome message through MD5
110                 md5.update(self.get_ftp_welcome())
111
112             md5.update(content)
113             bookmark.md5 = str(md5)
114
115             if headers:
116                 try:
117                     content_type = headers["Content-Type"]
118                     self.log("   Content-Type: %s" % content_type)
119                     try:
120                         # extract charset from "text/html; foo; charset=UTF-8, bar; baz;"
121                         content_type, charset = content_type.split(';', 1)
122                         content_type = content_type.strip()
123                         charset = charset.split('=')[1].strip().split(',')[0]
124                         self.log("   HTTP charset   : %s" % charset)
125                     except (ValueError, IndexError):
126                         charset = None
127                         self.log("   no charset in Content-Type header")
128                     for ctype in ("text/html", "application/xhtml+xml"):
129                         if content_type.startswith(ctype):
130                             html = True
131                             break
132                     else:
133                         html = False
134                     if html:
135                         parser = parse_html(content, charset, self.log)
136                         if parser:
137                             bookmark.real_title = parser.title
138                             icon = parser.icon
139                         else:
140                             icon = None
141                         if not icon:
142                             icon = "/favicon.ico"
143                         icon_url = urljoin("%s://%s%s" % (url_type, url_host, url_path), icon)
144                         self.log("   looking for icon at: %s" % icon_url)
145                         if icon_url in icons:
146                             if icons[icon_url]:
147                                 bookmark.icon_href = icon_url
148                                 content_type, bookmark.icon = icons[icon_url]
149                                 self.log("   cached icon: %s" % content_type)
150                             else:
151                                 self.log("   cached icon: no icon")
152                         else:
153                             try:
154                                 _icon_url = icon_url
155                                 for i in range(8):
156                                     error, icon_redirect_code, icon_redirect_to, \
157                                         icon_headers, icon_data = \
158                                         self.get(bookmark, _icon_url)
159                                     if icon_redirect_code:
160                                         _icon_url = icon_redirect_to
161                                         self.log("   redirect to : %s" % _icon_url)
162                                     else:
163                                         if icon_data is None:
164                                             raise IOError("No icon")
165                                         break
166                                 else:
167                                     raise IOError("Too many redirects")
168                             except:
169                                 etype, emsg, tb = sys.exc_info()
170                                 self.log("   no icon        : %s %s" % (etype, emsg))
171                                 etype = emsg = tb = None
172                                 icons[icon_url] = None
173                             else:
174                                 content_type = icon_headers["Content-Type"]
175                                 if content_type.startswith("application/") \
176                                    or content_type.startswith("image/") \
177                                    or content_type.startswith("text/plain"):
178                                     bookmark.icon_href = icon_url
179                                     self.log("   got icon       : %s" % content_type)
180                                     if content_type.startswith("application/") \
181                                        or content_type.startswith("text/plain"):
182                                         self.log("   non-image content type, assume x-icon")
183                                         content_type = 'image/x-icon'
184                                     bookmark.icon = "data:%s;base64,%s" % (content_type, b64encode(icon_data))
185                                     icons[icon_url] = (content_type, bookmark.icon)
186                                 else:
187                                     self.log("   no icon        : bad content type '%s'" % content_type)
188                                     icons[icon_url] = None
189                         if parser and parser.refresh:
190                             refresh = parser.refresh
191                             try:
192                                 url = refresh.split('=', 1)[1]
193                             except IndexError:
194                                 url = "self"
195                             try:
196                                 timeout = float(refresh.split(';')[0])
197                             except (IndexError, ValueError):
198                                 self.set_redirect(bookmark, "html", "Bad redirect to %s (%s)" % (url, refresh))
199                             else:
200                                 try:
201                                     timeout = int(refresh.split(';')[0])
202                                 except ValueError:
203                                     pass  # float timeout
204                                 self.set_redirect(bookmark, "html", "%s (%s sec)" % (url, timeout))
205
206                 except KeyError as key:
207                     self.log("   no header: %s" % key)
208
209         except EOFError:
210             bookmark.error = "Unexpected EOF (FTP server closed connection)"
211             self.log('   EOF: %s' % bookmark.error)
212
213         except KeyboardInterrupt:
214             self.log("Keyboard interrupt (^C)")
215             return 0
216
217         except socket.error as e:
218             bookmark.error = get_error(e)
219             self.log(bookmark.error)
220
221         except:
222             import traceback
223             traceback.print_exc()
224             bookmark.error = "Exception!"
225             self.log('   Exception: %s' % bookmark.error)
226
227         finally:
228             self.finish_check_url(bookmark)
229
230         # Tested
231         return 1
232
233     def set_redirect(self, bookmark, errcode, newurl):
234         bookmark.moved = "(%s) to %s" % (reloc_dict[errcode], newurl)
235         self.log('   Moved: %s' % bookmark.moved)
236
237     def finish_check_url(self, bookmark):
238         start = self.start
239         bookmark.last_tested = str(start)
240         now = int(time.time())
241         bookmark.test_time = str(now - start)