2 Simple, strightforward robot
4 Written by Oleg BroytMann. Copyright (C) 2000-2007 PhiloSoft Design.
9 from base64 import b64encode
10 from urlparse import urljoin
12 from m_lib.net.www.util import parse_time
13 from m_lib.md5wrapper import md5wrapper
15 from bkmk_objects import Robot
16 from parse_html import parse_html
19 class RedirectException(Exception):
25 def __init__(self, errcode, newurl):
26 Exception.__init__(self, "(%s) to %s" % (self.reloc_dict[errcode], newurl))
30 class MyURLopener(urllib.URLopener):
31 # Error 302 -- relocated (temporarily)
32 def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
33 if headers.has_key('location'):
34 newurl = headers['location']
35 elif headers.has_key('uri'):
36 newurl = headers['uri']
39 raise RedirectException(errcode, newurl)
41 # Error 301 -- also relocated (permanently)
42 http_error_301 = http_error_302
44 # Error 401 -- authentication required
45 def http_error_401(self, url, fp, errcode, errmsg, headers, data=None):
46 raise IOError, ('http error', errcode, "Authentication required ", headers)
48 def http_error_default(self, url, fp, errcode, errmsg, headers):
52 raise IOError, ('http error', errcode, errmsg, headers)
55 urllib._urlopener = MyURLopener()
57 # Fake headers to pretend this is a real browser
58 _version = "Mozilla/5.0 (X11; U; Linux 2.6 i686; en) Gecko/20001221 Firefox/2.0.0"
59 urllib._urlopener.addheaders[0] = ('User-Agent', _version)
60 _version = "bookmarks_db (Python %d.%d.%d; urllib/%s)" % (
61 sys.version_info[0], sys.version_info[1], sys.version_info[2], urllib.__version__)
62 urllib._urlopener.addheader('X-User-Agent', _version)
63 urllib._urlopener.addheader('Referer', '')
65 urllib._urlopener.addheader('Connection', 'close')
66 urllib._urlopener.addheader('Accept', '*/*')
67 urllib._urlopener.addheader('Accept-Language', 'ru,en')
68 urllib._urlopener.addheader('Cache-Control', 'max-age=300')
72 if isinstance(msg, str):
78 s.append("'%s'" % str(i).replace('\n', "\\n"))
79 return "(%s)" % ' '.join(s)
82 urllib_ftpwrapper = urllib.ftpwrapper
85 class myftpwrapper(urllib_ftpwrapper):
86 def __init__(self, user, passwd, host, port, dirs):
87 urllib_ftpwrapper.__init__(self, user, passwd, host, port, dirs)
89 ftpcache_key = (user, host, port, '/'.join(dirs))
91 urllib.ftpwrapper = myftpwrapper
95 _welcome = urllib._urlopener.ftpcache[ftpcache_key].ftp.welcome
96 ftpcache_key = None # I am assuming there are no duplicate ftp URLs in db.
97 # If there are - ftpcache_key in prev line is invalid.
101 icons = {} # Icon cache; maps URL to a tuple (content type, data)
102 # or None if there is no icon.
104 class robot_simple(Robot):
105 def check_url(self, bookmark):
106 if not self.tempfname:
107 self.tempfname = bookmark.tempfname
110 self.start = int(time.time())
113 url_type, url_rest = urllib.splittype(bookmark.href)
114 url_host, url_path = urllib.splithost(url_rest)
115 url_path, url_tag = urllib.splittag(url_path)
117 # Set fake referer to the root of the site
118 urllib._urlopener.addheaders[2] = ('Referer', "%s://%s%s" % (url_type, url_host, url_path))
120 if bookmark.charset: urllib._urlopener.addheader('Accept-Charset', bookmark.charset)
121 fname, headers = urllib.urlretrieve("%s://%s%s" % (url_type, url_host, url_path), self.tempfname)
122 if bookmark.charset: del urllib._urlopener.addheaders[-1]
129 size = headers["Content-Length"]
134 last_modified = headers["Last-Modified"]
139 last_modified = parse_time(last_modified)
142 last_modified = str(int(last_modified))
144 last_modified = bookmark.last_visit
147 bookmark.last_modified = last_modified
150 if urllib._urlopener.type == "ftp": # Pass welcome message through MD5
151 md5.update(get_welcome())
153 md5.md5file(self.tempfname)
154 bookmark.md5 = str(md5)
158 content_type = headers["Content-Type"]
160 content_type, charset = content_type.split(';')
161 content_type = content_type.strip()
162 charset = charset.split('=')[1].strip()
163 self.log(" HTTP charset : %s" % charset)
164 except (ValueError, IndexError):
166 self.log(" no charset in Content-Type header")
167 if content_type == "text/html":
168 parser = parse_html(fname, charset, self.log)
169 bookmark.real_title = parser.title
171 refresh = parser.refresh
173 url = refresh.split('=', 1)[1]
177 timeout = float(refresh.split(';')[0])
178 except (IndexError, ValueError):
179 raise RedirectException("html", "Bad redirect to %s (%s)" % (url, refresh))
182 timeout = int(refresh.split(';')[0])
185 raise RedirectException("html", "%s (%s sec)" % (url, timeout))
190 icon = "/favicon.ico"
191 icon = urljoin("%s://%s%s" % (url_type, url_host, url_path), icon)
192 self.log(" looking for icon at: %s" % icon)
195 content_type, bookmark.icon = icons[icon]
196 self.log(" cached icon: %s" % content_type)
198 self.log(" cached icon: no icon")
204 fname, headers = urllib.urlretrieve(_icon)
205 except RedirectException, e:
207 self.log(" redirect to : %s" % _icon)
211 raise IOError("Too many redirects")
213 etype, emsg, tb = sys.exc_info()
214 self.log(" no icon : %s %s" % (etype, emsg))
220 content_type = headers["Content-Type"]
221 if content_type.startswith("image/"):
222 icon_file = open(fname, "rb")
223 icon = icon_file.read()
225 bookmark.icon = "data:%s;base64,%s" % (content_type, b64encode(icon))
226 self.log(" got icon : %s" % content_type)
227 icons[icon] = (content_type, bookmark.icon)
229 self.log(" no icon : bad content type '%s'" % content_type)
237 if (msg[0] == "http error") and (msg[1] == -1):
238 bookmark.no_error = "The server did not return any header - it is not an error, actually"
240 bookmark.error = get_error(msg)
243 bookmark.error = "Unexpected EOF (FTP server closed connection)"
245 except RedirectException, msg:
246 bookmark.moved = str(msg)
248 except KeyboardInterrupt:
253 traceback.print_exc()
254 bookmark.error = "Exception!"
257 self.finish_check_url(bookmark)
263 def finish_check_url(self, bookmark):
264 # Calculate these attributes even in case of an error
265 if os.path.exists(self.tempfname):
266 size = str(os.path.getsize(self.tempfname))
272 bookmark.last_tested = str(start)
274 now = int(time.time())
275 bookmark.test_time = str(now - start)