]> git.phdru.name Git - bookmarks_db.git/blob - Robots/bkmk_rsimple.py
Version 3.3.1.
[bookmarks_db.git] / Robots / bkmk_rsimple.py
1 """
2    Simple, strightforward robot; guaranteed to has problems with timeouts :)
3
4    Written by BroytMann, Mar 2000 - Aug 2002. Copyright (C) 2000-2002 PhiloSoft Design
5 """
6
7
8 class RedirectException(Exception):
9    reloc_dict = {
10       301: "perm.",
11       302: "temp.",
12       "html": "html"
13    }
14    def __init__(self, errcode, newurl):
15       Exception.__init__(self, "(%s) to %s" % (self.reloc_dict[errcode], newurl))
16
17
18 import string, os
19 import time, urllib
20 from m_lib.www.util import parse_time
21 from m_lib.md5wrapper import md5wrapper
22
23
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']
31       else:
32          newurl = "Nowhere"
33       raise RedirectException(errcode, newurl)
34
35    # Error 301 -- also relocated (permanently)
36    http_error_301 = http_error_302
37
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)
41
42
43 urllib._urlopener = MyURLopener()
44
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)
48
49
50 def get_error(msg):
51    if type(msg) == type(""):
52       return msg
53
54    else:
55       s = []
56       for i in msg:
57          s.append("'%s'" % string.join(string.split(str(i), "\n"), "\\n"))
58       return "(%s)" % string.join(s)
59
60
61 urllib_ftpwrapper = urllib.ftpwrapper
62 ftpcache_key = None
63
64 class myftpwrapper(urllib_ftpwrapper):
65    def __init__(self, user, passwd, host, port, dirs):
66       urllib_ftpwrapper.__init__(self, user, passwd, host, port, dirs)
67       global ftpcache_key
68       ftpcache_key = (user, host, port, string.join(dirs, '/'))
69
70 urllib.ftpwrapper = myftpwrapper
71
72 def get_welcome():
73    global ftpcache_key
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.
77    return _welcome
78
79
80 from bkmk_objects import Robot
81 from parse_html import parse_html
82
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
87
88       try:
89          try:
90             self.start = int(time.time())
91             url_host, url_path = urllib.splithost(url_rest)
92             url_path, url_tag  = urllib.splittag(url_path)
93
94             fname, headers = urllib.urlretrieve("%s://%s%s" % (url_type, url_host, url_path), self.tempfname)
95
96             size = 0
97             last_modified = None
98
99             if headers:
100                try:
101                   size = headers["Content-Length"]
102                except KeyError:
103                   pass
104
105                try:
106                   last_modified = headers["Last-Modified"]
107                except KeyError:
108                   pass
109
110                if last_modified:
111                   last_modified = parse_time(last_modified)
112
113             if last_modified:
114                last_modified = str(int(last_modified))
115             else:
116                last_modified = bookmark.last_visit
117
118             bookmark.size = size
119             bookmark.last_modified = last_modified
120
121             md5 = md5wrapper()
122             if urllib._urlopener.type == "ftp": # Pass welcome message through MD5
123                md5.update(get_welcome())
124
125             md5.md5file(self.tempfname)
126             bookmark.md5 = str(md5)
127
128             if headers:
129                try:
130                   content_type = headers["Content-Type"]
131                   try:
132                      content_type, charset = content_type.split(';')
133                      content_type = content_type.strip()
134                      charset = charset.split('=')[1].strip()
135                      if self.log: self.log("   HTTP charset   : %s" % charset)
136                   except (ValueError, IndexError):
137                      charset = None
138                      if self.log: self.log("   no charset in Content-Type header")
139                   if content_type == "text/html":
140                      parser = parse_html(fname, charset, self.log)
141                      title = parser.title.replace('\r', '').replace('\n', ' ').strip()
142                      bookmark.real_title = parser.unescape(title)
143                      if self.log: self.log("   final title    : %s" % bookmark.real_title)
144                      if parser.refresh:
145                         refresh = parser.refresh
146                         try:
147                            timeout = int(refresh.split(';')[0])
148                         except (IndexError, ValueError):
149                            timeout = "ERROR"
150                         try:
151                            url = refresh.split('=', 1)[1]
152                         except IndexError:
153                            url = "self"
154                         raise RedirectException("html", "%s (%d sec)" % (url, timeout))
155                except KeyError:
156                   pass
157
158          except IOError, msg:
159             if (msg[0] == "http error") and (msg[1] == -1):
160                bookmark.no_error = "The server did not return any header - it is not an error, actually"
161             else:
162                bookmark.error = get_error(msg)
163
164          except EOFError:
165             bookmark.error = "Unexpected EOF (FTP server closed connection)"
166
167          except RedirectException, msg:
168             bookmark.moved = str(msg)
169
170          except KeyboardInterrupt:
171             return 0
172
173       finally:
174          self.finish_check_url(bookmark)
175
176       # Tested
177       return 1
178
179
180    def finish_check_url(self, bookmark):
181       # Calculate these attributes even in case of an error
182       if os.path.exists(self.tempfname):
183          size = str(os.stat(self.tempfname).st_size)
184          if size[-1] == 'L':
185             size = size[:-1]
186          bookmark.size = size
187
188       start = self.start
189       bookmark.last_tested = str(start)
190
191       now = int(time.time())
192       bookmark.test_time = str(now - start)