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 # Some sites allow only Mozilla-compatible browsers; way to stop robots?
48 server_version = "Mozilla/3.0 (compatible; Python-urllib/%s)" % urllib.__version__
49 urllib._urlopener.addheaders[0] = ('User-agent', server_version)
53 if type(msg) == type(""):
59 s.append("'%s'" % string.join(string.split(str(i), "\n"), "\\n"))
60 return "(%s)" % string.join(s)
63 urllib_ftpwrapper = urllib.ftpwrapper
66 class myftpwrapper(urllib_ftpwrapper):
67 def __init__(self, user, passwd, host, port, dirs):
68 urllib_ftpwrapper.__init__(self, user, passwd, host, port, dirs)
70 ftpcache_key = (user, host, port, string.join(dirs, '/'))
72 urllib.ftpwrapper = myftpwrapper
76 _welcome = urllib._urlopener.ftpcache[ftpcache_key].ftp.welcome
77 ftpcache_key = None # I am assuming there are no duplicate ftp URLs in db.
78 # If there are - ftpcache_key in prev line is invalid.
82 from bkmk_objects import Robot
83 from parse_html import parse_html
85 class robot_simple(Robot):
86 def check_url(self, bookmark):
87 if not self.tempfname:
88 self.tempfname = bookmark.tempfname
92 self.start = int(time.time())
95 url_type, url_rest = urllib.splittype(bookmark.href)
96 url_host, url_path = urllib.splithost(url_rest)
97 url_path, url_tag = urllib.splittag(url_path)
99 if bookmark.charset: urllib._urlopener.addheader('Accept-Charset', bookmark.charset)
100 fname, headers = urllib.urlretrieve("%s://%s%s" % (url_type, url_host, url_path), self.tempfname)
101 if bookmark.charset: del urllib._urlopener.addheaders[-1]
108 size = headers["Content-Length"]
113 last_modified = headers["Last-Modified"]
118 last_modified = parse_time(last_modified)
121 last_modified = str(int(last_modified))
123 last_modified = bookmark.last_visit
126 bookmark.last_modified = last_modified
129 if urllib._urlopener.type == "ftp": # Pass welcome message through MD5
130 md5.update(get_welcome())
132 md5.md5file(self.tempfname)
133 bookmark.md5 = str(md5)
137 content_type = headers["Content-Type"]
139 content_type, charset = content_type.split(';')
140 content_type = content_type.strip()
141 charset = charset.split('=')[1].strip()
142 if self.log: self.log(" HTTP charset : %s" % charset)
143 except (ValueError, IndexError):
145 if self.log: self.log(" no charset in Content-Type header")
146 if content_type == "text/html":
147 parser = parse_html(fname, charset, self.log)
148 title = parser.title.replace('\r', '').replace('\n', ' ').strip()
149 bookmark.real_title = parser.unescape(title)
150 if self.log: self.log(" final title : %s" % bookmark.real_title)
152 refresh = parser.refresh
154 url = refresh.split('=', 1)[1]
158 timeout = int(refresh.split(';')[0])
159 except (IndexError, ValueError):
162 raise RedirectException("html", "Bad redirect to %s (%s)" % (url, refresh))
164 raise RedirectException("html", "%s (%d sec)" % (url, timeout))
169 icon = "/favicon.ico"
170 icon = urljoin("%s://%s%s" % (url_type, url_host, url_path), icon)
171 if self.log: self.log(" icon : %s" % icon)
173 fname, headers = urllib.urlretrieve(icon)
175 etype, emsg, tb = sys.exc_info()
176 if self.log: self.log(" no icon : %s %s" % (etype, emsg))
181 icon_file = open(fname, "rb")
182 icon = icon_file.read()
185 content_type = headers["Content-Type"]
186 if content_type.startswith("image/"):
187 bookmark.icon = "data:%s;base64,%s" % (content_type, b64encode(icon))
193 if (msg[0] == "http error") and (msg[1] == -1):
194 bookmark.no_error = "The server did not return any header - it is not an error, actually"
196 bookmark.error = get_error(msg)
199 bookmark.error = "Unexpected EOF (FTP server closed connection)"
201 except RedirectException, msg:
202 bookmark.moved = str(msg)
204 except KeyboardInterrupt:
208 self.finish_check_url(bookmark)
214 def finish_check_url(self, bookmark):
215 # Calculate these attributes even in case of an error
216 if os.path.exists(self.tempfname):
217 size = str(os.path.getsize(self.tempfname))
223 bookmark.last_tested = str(start)
225 now = int(time.time())
226 bookmark.test_time = str(now - start)