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