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))
27 class MyURLopener(urllib.URLopener):
28 # Error 302 -- relocated (temporarily)
29 def http_error_302(self, url, fp, errcode, errmsg, headers, data=None):
30 if headers.has_key('location'):
31 newurl = headers['location']
32 elif headers.has_key('uri'):
33 newurl = headers['uri']
36 raise RedirectException(errcode, newurl)
38 # Error 301 -- also relocated (permanently)
39 http_error_301 = http_error_302
41 # Error 401 -- authentication required
42 def http_error_401(self, url, fp, errcode, errmsg, headers, data=None):
43 raise IOError, ('http error', errcode, "Authentication required ", headers)
46 urllib._urlopener = MyURLopener()
48 # Fake headers to pretend this is a real browser
49 _version = "Links (2.1; Linux 2.6 i686; 80x25)"
50 urllib._urlopener.addheaders[0] = ('User-Agent', _version)
51 _version = "bookmarks_db (Python %d.%d.%d; urllib/%s)" % (sys.version_info[:3], urllib.__version__)
52 urllib._urlopener.addheader('X-User-Agent', _version)
54 urllib._urlopener.addheader('Connection', 'close')
55 urllib._urlopener.addheader('Content-Length', '0')
56 urllib._urlopener.addheader('Accept', '*/*')
57 urllib._urlopener.addheader('Accept-Language', 'ru,en')
58 urllib._urlopener.addheader('Cache-Control', 'max-age=300')
59 urllib._urlopener.addheader('Referer', 'http://www.yahoo.com/')
63 if type(msg) == type(""):
69 s.append("'%s'" % string.join(string.split(str(i), "\n"), "\\n"))
70 return "(%s)" % string.join(s)
73 urllib_ftpwrapper = urllib.ftpwrapper
76 class myftpwrapper(urllib_ftpwrapper):
77 def __init__(self, user, passwd, host, port, dirs):
78 urllib_ftpwrapper.__init__(self, user, passwd, host, port, dirs)
80 ftpcache_key = (user, host, port, string.join(dirs, '/'))
82 urllib.ftpwrapper = myftpwrapper
86 _welcome = urllib._urlopener.ftpcache[ftpcache_key].ftp.welcome
87 ftpcache_key = None # I am assuming there are no duplicate ftp URLs in db.
88 # If there are - ftpcache_key in prev line is invalid.
92 from bkmk_objects import Robot
93 from parse_html import parse_html
95 class robot_simple(Robot):
96 def check_url(self, bookmark):
97 if not self.tempfname:
98 self.tempfname = bookmark.tempfname
102 self.start = int(time.time())
105 url_type, url_rest = urllib.splittype(bookmark.href)
106 url_host, url_path = urllib.splithost(url_rest)
107 url_path, url_tag = urllib.splittag(url_path)
109 if bookmark.charset: urllib._urlopener.addheader('Accept-Charset', bookmark.charset)
110 fname, headers = urllib.urlretrieve("%s://%s%s" % (url_type, url_host, url_path), self.tempfname)
111 if bookmark.charset: del urllib._urlopener.addheaders[-1]
118 size = headers["Content-Length"]
123 last_modified = headers["Last-Modified"]
128 last_modified = parse_time(last_modified)
131 last_modified = str(int(last_modified))
133 last_modified = bookmark.last_visit
136 bookmark.last_modified = last_modified
139 if urllib._urlopener.type == "ftp": # Pass welcome message through MD5
140 md5.update(get_welcome())
142 md5.md5file(self.tempfname)
143 bookmark.md5 = str(md5)
147 content_type = headers["Content-Type"]
149 content_type, charset = content_type.split(';')
150 content_type = content_type.strip()
151 charset = charset.split('=')[1].strip()
152 if self.log: self.log(" HTTP charset : %s" % charset)
153 except (ValueError, IndexError):
155 if self.log: self.log(" no charset in Content-Type header")
156 if content_type == "text/html":
157 parser = parse_html(fname, charset, self.log)
158 bookmark.real_title = parser.title
160 refresh = parser.refresh
162 url = refresh.split('=', 1)[1]
166 timeout = float(refresh.split(';')[0])
167 except (IndexError, ValueError):
168 raise RedirectException("html", "Bad redirect to %s (%s)" % (url, refresh))
171 timeout = int(refresh.split(';')[0])
174 raise RedirectException("html", "%s (%s sec)" % (url, timeout))
179 icon = "/favicon.ico"
180 icon = urljoin("%s://%s%s" % (url_type, url_host, url_path), icon)
181 if self.log: self.log(" looking for icon at: %s" % icon)
185 fname, headers = urllib.urlretrieve(icon)
186 except RedirectException, e:
188 if self.log: self.log(" redirect to : %s" % icon)
192 raise IOError("Too many redirects")
194 etype, emsg, tb = sys.exc_info()
195 if self.log: self.log(" no icon : %s %s" % (etype, emsg))
200 content_type = headers["Content-Type"]
201 if content_type.startswith("image/"):
202 icon_file = open(fname, "rb")
203 icon = icon_file.read()
205 bookmark.icon = "data:%s;base64,%s" % (content_type, b64encode(icon))
206 if self.log: self.log(" got icon : %s" % content_type)
208 if self.log: self.log(" no icon : bad content type '%s'" % content_type)
215 if (msg[0] == "http error") and (msg[1] == -1):
216 bookmark.no_error = "The server did not return any header - it is not an error, actually"
218 bookmark.error = get_error(msg)
221 bookmark.error = "Unexpected EOF (FTP server closed connection)"
223 except RedirectException, msg:
224 bookmark.moved = str(msg)
226 except KeyboardInterrupt:
230 self.finish_check_url(bookmark)
236 def finish_check_url(self, bookmark):
237 # Calculate these attributes even in case of an error
238 if os.path.exists(self.tempfname):
239 size = str(os.path.getsize(self.tempfname))
245 bookmark.last_tested = str(start)
247 now = int(time.time())
248 bookmark.test_time = str(now - start)