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