2 Simple, strightforward robot; guaranteed to has problems with timeouts :)
4 Written by BroytMann, Mar 2000 - Sep 2007. Copyright (C) 2000-2007 PhiloSoft Design
8 class RedirectException(Exception):
14 def __init__(self, errcode, newurl):
15 Exception.__init__(self, "(%s) to %s" % (self.reloc_dict[errcode], newurl))
20 from m_lib.net.www.util import parse_time
21 from m_lib.md5wrapper import md5wrapper
24 class MyURLopener(urllib.URLopener):
25 # Error 302 -- relocated (temporarily)
26 def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
27 if headers.has_key('location'):
28 newurl = headers['location']
29 elif headers.has_key('uri'):
30 newurl = headers['uri']
33 raise RedirectException(errcode, newurl)
35 # Error 301 -- also relocated (permanently)
36 http_error_301 = http_error_302
38 # Error 401 -- authentication required
39 def http_error_401(self, url, fp, errcode, errmsg, headers, data=None):
40 raise IOError, ('http error', errcode, "Authentication required ", headers)
43 urllib._urlopener = MyURLopener()
45 # Some sites allow only Mozilla-compatible browsers; way to stop robots?
46 server_version = "Mozilla/3.0 (compatible; Python-urllib/%s)" % urllib.__version__
47 urllib._urlopener.addheaders[0] = ('User-agent', server_version)
51 if type(msg) == type(""):
57 s.append("'%s'" % string.join(string.split(str(i), "\n"), "\\n"))
58 return "(%s)" % string.join(s)
61 urllib_ftpwrapper = urllib.ftpwrapper
64 class myftpwrapper(urllib_ftpwrapper):
65 def __init__(self, user, passwd, host, port, dirs):
66 urllib_ftpwrapper.__init__(self, user, passwd, host, port, dirs)
68 ftpcache_key = (user, host, port, string.join(dirs, '/'))
70 urllib.ftpwrapper = myftpwrapper
74 _welcome = urllib._urlopener.ftpcache[ftpcache_key].ftp.welcome
75 ftpcache_key = None # I am assuming there are no duplicate ftp URLs in db.
76 # If there are - ftpcache_key in prev line is invalid.
80 from bkmk_objects import Robot
81 from parse_html import parse_html
83 class robot_simple(Robot):
84 def check_url(self, bookmark, url_type, url_rest):
85 if not self.tempfname:
86 self.tempfname = bookmark.tempfname
90 self.start = int(time.time())
91 url_host, url_path = urllib.splithost(url_rest)
92 url_path, url_tag = urllib.splittag(url_path)
94 if bookmark.charset: urllib._urlopener.addheader('Accept-Charset', bookmark.charset)
95 fname, headers = urllib.urlretrieve("%s://%s%s" % (url_type, url_host, url_path), self.tempfname)
96 if bookmark.charset: del urllib._urlopener.addheaders[-1]
103 size = headers["Content-Length"]
108 last_modified = headers["Last-Modified"]
113 last_modified = parse_time(last_modified)
116 last_modified = str(int(last_modified))
118 last_modified = bookmark.last_visit
121 bookmark.last_modified = last_modified
124 if urllib._urlopener.type == "ftp": # Pass welcome message through MD5
125 md5.update(get_welcome())
127 md5.md5file(self.tempfname)
128 bookmark.md5 = str(md5)
132 content_type = headers["Content-Type"]
134 content_type, charset = content_type.split(';')
135 content_type = content_type.strip()
136 charset = charset.split('=')[1].strip()
137 if self.log: self.log(" HTTP charset : %s" % charset)
138 except (ValueError, IndexError):
140 if self.log: self.log(" no charset in Content-Type header")
141 if content_type == "text/html":
142 parser = parse_html(fname, charset, self.log)
143 title = parser.title.replace('\r', '').replace('\n', ' ').strip()
144 bookmark.real_title = parser.unescape(title)
145 if self.log: self.log(" final title : %s" % bookmark.real_title)
147 refresh = parser.refresh
149 url = refresh.split('=', 1)[1]
153 timeout = int(refresh.split(';')[0])
154 except (IndexError, ValueError):
157 raise RedirectException("html", "Bad redirect to %s (%s)" % (url, refresh))
159 raise RedirectException("html", "%s (%d sec)" % (url, timeout))
164 if (msg[0] == "http error") and (msg[1] == -1):
165 bookmark.no_error = "The server did not return any header - it is not an error, actually"
167 bookmark.error = get_error(msg)
170 bookmark.error = "Unexpected EOF (FTP server closed connection)"
172 except RedirectException, msg:
173 bookmark.moved = str(msg)
175 except KeyboardInterrupt:
179 self.finish_check_url(bookmark)
185 def finish_check_url(self, bookmark):
186 # Calculate these attributes even in case of an error
187 if os.path.exists(self.tempfname):
188 size = str(os.path.getsize(self.tempfname))
194 bookmark.last_tested = str(start)
196 now = int(time.time())
197 bookmark.test_time = str(now - start)