2 Simple, strightforward robot
4 Written by Oleg BroytMann. Copyright (C) 2000-2007 PhiloSoft Design.
10 from urlparse import urljoin
11 from m_lib.net.www.util import parse_time
12 from m_lib.md5wrapper import md5wrapper
15 class RedirectException(Exception):
21 def __init__(self, errcode, newurl):
22 Exception.__init__(self, "(%s) to %s" % (self.reloc_dict[errcode], newurl))
25 class MyURLopener(urllib.URLopener):
26 # Error 302 -- relocated (temporarily)
27 def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
28 if headers.has_key('location'):
29 newurl = headers['location']
30 elif headers.has_key('uri'):
31 newurl = headers['uri']
34 raise RedirectException(errcode, newurl)
36 # Error 301 -- also relocated (permanently)
37 http_error_301 = http_error_302
39 # Error 401 -- authentication required
40 def http_error_401(self, url, fp, errcode, errmsg, headers, data=None):
41 raise IOError, ('http error', errcode, "Authentication required ", headers)
44 urllib._urlopener = MyURLopener()
46 # Some sites allow only Mozilla-compatible browsers; way to stop robots?
47 server_version = "Mozilla/3.0 (compatible; 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, url_type, url_rest):
86 if not self.tempfname:
87 self.tempfname = bookmark.tempfname
91 self.start = int(time.time())
92 url_host, url_path = urllib.splithost(url_rest)
93 url_path, url_tag = urllib.splittag(url_path)
95 if bookmark.charset: urllib._urlopener.addheader('Accept-Charset', bookmark.charset)
96 fname, headers = urllib.urlretrieve("%s://%s%s" % (url_type, url_host, url_path), self.tempfname)
97 if bookmark.charset: del urllib._urlopener.addheaders[-1]
104 size = headers["Content-Length"]
109 last_modified = headers["Last-Modified"]
114 last_modified = parse_time(last_modified)
117 last_modified = str(int(last_modified))
119 last_modified = bookmark.last_visit
122 bookmark.last_modified = last_modified
125 if urllib._urlopener.type == "ftp": # Pass welcome message through MD5
126 md5.update(get_welcome())
128 md5.md5file(self.tempfname)
129 bookmark.md5 = str(md5)
133 content_type = headers["Content-Type"]
135 content_type, charset = content_type.split(';')
136 content_type = content_type.strip()
137 charset = charset.split('=')[1].strip()
138 if self.log: self.log(" HTTP charset : %s" % charset)
139 except (ValueError, IndexError):
141 if self.log: self.log(" no charset in Content-Type header")
142 if content_type == "text/html":
143 parser = parse_html(fname, charset, self.log)
144 title = parser.title.replace('\r', '').replace('\n', ' ').strip()
145 bookmark.real_title = parser.unescape(title)
146 if self.log: self.log(" final title : %s" % bookmark.real_title)
148 refresh = parser.refresh
150 url = refresh.split('=', 1)[1]
154 timeout = int(refresh.split(';')[0])
155 except (IndexError, ValueError):
158 raise RedirectException("html", "Bad redirect to %s (%s)" % (url, refresh))
160 raise RedirectException("html", "%s (%d sec)" % (url, timeout))
163 icon = "/favicon.ico"
164 icon = urljoin("%s://%s" % (url_type, url_host), icon)
165 if self.log: self.log(" icon : %s" % icon)
170 if (msg[0] == "http error") and (msg[1] == -1):
171 bookmark.no_error = "The server did not return any header - it is not an error, actually"
173 bookmark.error = get_error(msg)
176 bookmark.error = "Unexpected EOF (FTP server closed connection)"
178 except RedirectException, msg:
179 bookmark.moved = str(msg)
181 except KeyboardInterrupt:
185 self.finish_check_url(bookmark)
191 def finish_check_url(self, bookmark):
192 # Calculate these attributes even in case of an error
193 if os.path.exists(self.tempfname):
194 size = str(os.path.getsize(self.tempfname))
200 bookmark.last_tested = str(start)
202 now = int(time.time())
203 bookmark.test_time = str(now - start)