2 Simple, strightforward robot
4 Written by Oleg BroytMann. Copyright (C) 2000-2007 PhiloSoft Design.
10 from base64 import b64encode
11 from urlparse import urljoin
12 from m_lib.net.www.util import parse_time
13 from m_lib.md5wrapper import md5wrapper
16 class RedirectException(Exception):
22 def __init__(self, errcode, newurl):
23 Exception.__init__(self, "(%s) to %s" % (self.reloc_dict[errcode], newurl))
26 class MyURLopener(urllib.URLopener):
27 # Error 302 -- relocated (temporarily)
28 def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
29 if headers.has_key('location'):
30 newurl = headers['location']
31 elif headers.has_key('uri'):
32 newurl = headers['uri']
35 raise RedirectException(errcode, newurl)
37 # Error 301 -- also relocated (permanently)
38 http_error_301 = http_error_302
40 # Error 401 -- authentication required
41 def http_error_401(self, url, fp, errcode, errmsg, headers, data=None):
42 raise IOError, ('http error', errcode, "Authentication required ", headers)
45 urllib._urlopener = MyURLopener()
47 server_version = "bookmarks_db (Python-urllib/%s)" % urllib.__version__
48 urllib._urlopener.addheaders[0] = ('User-agent', server_version)
52 if type(msg) == type(""):
58 s.append("'%s'" % string.join(string.split(str(i), "\n"), "\\n"))
59 return "(%s)" % string.join(s)
62 urllib_ftpwrapper = urllib.ftpwrapper
65 class myftpwrapper(urllib_ftpwrapper):
66 def __init__(self, user, passwd, host, port, dirs):
67 urllib_ftpwrapper.__init__(self, user, passwd, host, port, dirs)
69 ftpcache_key = (user, host, port, string.join(dirs, '/'))
71 urllib.ftpwrapper = myftpwrapper
75 _welcome = urllib._urlopener.ftpcache[ftpcache_key].ftp.welcome
76 ftpcache_key = None # I am assuming there are no duplicate ftp URLs in db.
77 # If there are - ftpcache_key in prev line is invalid.
81 from bkmk_objects import Robot
82 from parse_html import parse_html
84 class robot_simple(Robot):
85 def check_url(self, bookmark):
86 if not self.tempfname:
87 self.tempfname = bookmark.tempfname
91 self.start = int(time.time())
94 url_type, url_rest = urllib.splittype(bookmark.href)
95 url_host, url_path = urllib.splithost(url_rest)
96 url_path, url_tag = urllib.splittag(url_path)
98 if bookmark.charset: urllib._urlopener.addheader('Accept-Charset', bookmark.charset)
99 fname, headers = urllib.urlretrieve("%s://%s%s" % (url_type, url_host, url_path), self.tempfname)
100 if bookmark.charset: del urllib._urlopener.addheaders[-1]
107 size = headers["Content-Length"]
112 last_modified = headers["Last-Modified"]
117 last_modified = parse_time(last_modified)
120 last_modified = str(int(last_modified))
122 last_modified = bookmark.last_visit
125 bookmark.last_modified = last_modified
128 if urllib._urlopener.type == "ftp": # Pass welcome message through MD5
129 md5.update(get_welcome())
131 md5.md5file(self.tempfname)
132 bookmark.md5 = str(md5)
136 content_type = headers["Content-Type"]
138 content_type, charset = content_type.split(';')
139 content_type = content_type.strip()
140 charset = charset.split('=')[1].strip()
141 if self.log: self.log(" HTTP charset : %s" % charset)
142 except (ValueError, IndexError):
144 if self.log: self.log(" no charset in Content-Type header")
145 if content_type == "text/html":
146 parser = parse_html(fname, charset, self.log)
147 bookmark.real_title = parser.title
149 refresh = parser.refresh
151 url = refresh.split('=', 1)[1]
155 timeout = float(refresh.split(';')[0])
156 except (IndexError, ValueError):
157 raise RedirectException("html", "Bad redirect to %s (%s)" % (url, refresh))
159 raise RedirectException("html", "%s (%s sec)" % (url, timeout))
164 icon = "/favicon.ico"
165 icon = urljoin("%s://%s%s" % (url_type, url_host, url_path), icon)
166 if self.log: self.log(" icon : %s" % icon)
168 fname, headers = urllib.urlretrieve(icon)
170 etype, emsg, tb = sys.exc_info()
171 if self.log: self.log(" no icon : %s %s" % (etype, emsg))
176 content_type = headers["Content-Type"]
177 if content_type.startswith("image/"):
178 icon_file = open(fname, "rb")
179 icon = icon_file.read()
181 bookmark.icon = "data:%s;base64,%s" % (content_type, b64encode(icon))
183 if self.log: self.log(" no icon : %s" % content_type)
190 if (msg[0] == "http error") and (msg[1] == -1):
191 bookmark.no_error = "The server did not return any header - it is not an error, actually"
193 bookmark.error = get_error(msg)
196 bookmark.error = "Unexpected EOF (FTP server closed connection)"
198 except RedirectException, msg:
199 bookmark.moved = str(msg)
201 except KeyboardInterrupt:
205 self.finish_check_url(bookmark)
211 def finish_check_url(self, bookmark):
212 # Calculate these attributes even in case of an error
213 if os.path.exists(self.tempfname):
214 size = str(os.path.getsize(self.tempfname))
220 bookmark.last_tested = str(start)
222 now = int(time.time())
223 bookmark.test_time = str(now - start)