]> git.phdru.name Git - bookmarks_db.git/blob - Robots/bkmk_rsimple.py
Convert redirect timeout to int if possible.
[bookmarks_db.git] / Robots / bkmk_rsimple.py
1 """
2    Simple, strightforward robot
3
4    Written by Oleg BroytMann. Copyright (C) 2000-2007 PhiloSoft Design.
5 """
6
7
8 import sys, os, string
9 import time, urllib
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
14
15
16 class RedirectException(Exception):
17    reloc_dict = {
18       301: "perm.",
19       302: "temp.",
20       "html": "html"
21    }
22    def __init__(self, errcode, newurl):
23       Exception.__init__(self, "(%s) to %s" % (self.reloc_dict[errcode], newurl))
24
25
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']
33       else:
34          newurl = "Nowhere"
35       raise RedirectException(errcode, newurl)
36
37    # Error 301 -- also relocated (permanently)
38    http_error_301 = http_error_302
39
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)
43
44
45 urllib._urlopener = MyURLopener()
46
47 server_version = "bookmarks_db (Python-urllib/%s)" % urllib.__version__
48 urllib._urlopener.addheaders[0] = ('User-agent', server_version)
49
50
51 def get_error(msg):
52    if type(msg) == type(""):
53       return msg
54
55    else:
56       s = []
57       for i in msg:
58          s.append("'%s'" % string.join(string.split(str(i), "\n"), "\\n"))
59       return "(%s)" % string.join(s)
60
61
62 urllib_ftpwrapper = urllib.ftpwrapper
63 ftpcache_key = None
64
65 class myftpwrapper(urllib_ftpwrapper):
66    def __init__(self, user, passwd, host, port, dirs):
67       urllib_ftpwrapper.__init__(self, user, passwd, host, port, dirs)
68       global ftpcache_key
69       ftpcache_key = (user, host, port, string.join(dirs, '/'))
70
71 urllib.ftpwrapper = myftpwrapper
72
73 def get_welcome():
74    global ftpcache_key
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.
78    return _welcome
79
80
81 from bkmk_objects import Robot
82 from parse_html import parse_html
83
84 class robot_simple(Robot):
85    def check_url(self, bookmark):
86       if not self.tempfname:
87          self.tempfname = bookmark.tempfname
88
89       try:
90          try:
91             self.start = int(time.time())
92             bookmark.icon = None
93
94             url_type, url_rest = urllib.splittype(bookmark.href)
95             url_host, url_path = urllib.splithost(url_rest)
96             url_path, url_tag  = urllib.splittag(url_path)
97
98             if bookmark.charset: urllib._urlopener.addheader('Accept-Charset', bookmark.charset)
99             fname, headers = urllib.urlretrieve("%s://%s%s" % (url_type, url_host, url_path), self.tempfname)
100             if bookmark.charset: del urllib._urlopener.addheaders[-1]
101
102             size = 0
103             last_modified = None
104
105             if headers:
106                try:
107                   size = headers["Content-Length"]
108                except KeyError:
109                   pass
110
111                try:
112                   last_modified = headers["Last-Modified"]
113                except KeyError:
114                   pass
115
116                if last_modified:
117                   last_modified = parse_time(last_modified)
118
119             if last_modified:
120                last_modified = str(int(last_modified))
121             else:
122                last_modified = bookmark.last_visit
123
124             bookmark.size = size
125             bookmark.last_modified = last_modified
126
127             md5 = md5wrapper()
128             if urllib._urlopener.type == "ftp": # Pass welcome message through MD5
129                md5.update(get_welcome())
130
131             md5.md5file(self.tempfname)
132             bookmark.md5 = str(md5)
133
134             if headers:
135                try:
136                   content_type = headers["Content-Type"]
137                   try:
138                      content_type, charset = content_type.split(';')
139                      content_type = content_type.strip()
140                      charset = charset.split('=')[1].strip()
141                      if self.log: self.log("   HTTP charset   : %s" % charset)
142                   except (ValueError, IndexError):
143                      charset = None
144                      if self.log: self.log("   no charset in Content-Type header")
145                   if content_type == "text/html":
146                      parser = parse_html(fname, charset, self.log)
147                      bookmark.real_title = parser.title
148                      if parser.refresh:
149                         refresh = parser.refresh
150                         try:
151                            url = refresh.split('=', 1)[1]
152                         except IndexError:
153                            url = "self"
154                         try:
155                            timeout = float(refresh.split(';')[0])
156                         except (IndexError, ValueError):
157                            raise RedirectException("html", "Bad redirect to %s (%s)" % (url, refresh))
158                         else:
159                            try:
160                               timeout = int(refresh.split(';')[0])
161                            except ValueError:
162                               pass # float timeout
163                            raise RedirectException("html", "%s (%s sec)" % (url, timeout))
164
165                      # Get favicon.ico
166                      icon = parser.icon
167                      if not icon:
168                         icon = "/favicon.ico"
169                      icon = urljoin("%s://%s%s" % (url_type, url_host, url_path), icon)
170                      if self.log: self.log("   icon           : %s" % icon)
171                      try:
172                         fname, headers = urllib.urlretrieve(icon)
173                      except:
174                         etype, emsg, tb = sys.exc_info()
175                         if self.log: self.log("   no icon        : %s %s" % (etype, emsg))
176                         etype = None
177                         emsg = None
178                         tb = None
179                      else:
180                         content_type = headers["Content-Type"]
181                         if content_type.startswith("image/"):
182                            icon_file = open(fname, "rb")
183                            icon = icon_file.read()
184                            icon_file.close()
185                            bookmark.icon = "data:%s;base64,%s" % (content_type, b64encode(icon))
186                         else:
187                            if self.log: self.log("   no icon        : %s" % content_type)
188                         os.remove(fname)
189
190                except KeyError:
191                   pass
192
193          except IOError, msg:
194             if (msg[0] == "http error") and (msg[1] == -1):
195                bookmark.no_error = "The server did not return any header - it is not an error, actually"
196             else:
197                bookmark.error = get_error(msg)
198
199          except EOFError:
200             bookmark.error = "Unexpected EOF (FTP server closed connection)"
201
202          except RedirectException, msg:
203             bookmark.moved = str(msg)
204
205          except KeyboardInterrupt:
206             return 0
207
208       finally:
209          self.finish_check_url(bookmark)
210
211       # Tested
212       return 1
213
214
215    def finish_check_url(self, bookmark):
216       # Calculate these attributes even in case of an error
217       if os.path.exists(self.tempfname):
218          size = str(os.path.getsize(self.tempfname))
219          if size[-1] == 'L':
220             size = size[:-1]
221          bookmark.size = size
222
223       start = self.start
224       bookmark.last_tested = str(start)
225
226       now = int(time.time())
227       bookmark.test_time = str(now - start)