]> git.phdru.name Git - bookmarks_db.git/blob - Robots/bkmk_rsimple.py
Cache icons.
[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 import sys, os
8 import time, urllib
9 from base64 import b64encode
10 from urlparse import urljoin
11
12 from m_lib.net.www.util import parse_time
13 from m_lib.md5wrapper import md5wrapper
14
15 from bkmk_objects import Robot
16 from parse_html import parse_html
17
18
19 class RedirectException(Exception):
20    reloc_dict = {
21       301: "perm.",
22       302: "temp.",
23       "html": "html"
24    }
25    def __init__(self, errcode, newurl):
26       Exception.__init__(self, "(%s) to %s" % (self.reloc_dict[errcode], newurl))
27       self.url = newurl
28
29
30 class MyURLopener(urllib.URLopener):
31    # Error 302 -- relocated (temporarily)
32    def http_error_302(self, url, fp, errcode, errmsg, headers, data=None): 
33       if headers.has_key('location'):
34          newurl = headers['location']
35       elif headers.has_key('uri'):
36          newurl = headers['uri']
37       else:
38          newurl = "Nowhere"
39       raise RedirectException(errcode, newurl)
40
41    # Error 301 -- also relocated (permanently)
42    http_error_301 = http_error_302
43
44    # Error 401 -- authentication required
45    def http_error_401(self, url, fp, errcode, errmsg, headers, data=None): 
46       raise IOError, ('http error', errcode, "Authentication required ", headers)
47
48
49 urllib._urlopener = MyURLopener()
50
51 # Fake headers to pretend this is a real browser
52 _version = "Mozilla/5.0 (X11; U; Linux 2.6 i686; en) Gecko/20001221 Firefox/2.0.0"
53 urllib._urlopener.addheaders[0] = ('User-Agent', _version)
54 _version = "bookmarks_db (Python %d.%d.%d; urllib/%s)" % (
55    sys.version_info[0], sys.version_info[1], sys.version_info[2], urllib.__version__)
56 urllib._urlopener.addheader('X-User-Agent', _version)
57 urllib._urlopener.addheader('Referer', '')
58
59 urllib._urlopener.addheader('Connection', 'close')
60 urllib._urlopener.addheader('Accept', '*/*')
61 urllib._urlopener.addheader('Accept-Language', 'ru,en')
62 urllib._urlopener.addheader('Cache-Control', 'max-age=300')
63
64
65 def get_error(msg):
66    if isinstance(msg, str):
67       return msg
68
69    else:
70       s = []
71       for i in msg:
72          s.append("'%s'" % str(i).replace('\n', "\\n"))
73       return "(%s)" % ' '.join(s)
74
75
76 urllib_ftpwrapper = urllib.ftpwrapper
77 ftpcache_key = None
78
79 class myftpwrapper(urllib_ftpwrapper):
80    def __init__(self, user, passwd, host, port, dirs):
81       urllib_ftpwrapper.__init__(self, user, passwd, host, port, dirs)
82       global ftpcache_key
83       ftpcache_key = (user, host, port, tuple(dirs))
84
85 urllib.ftpwrapper = myftpwrapper
86
87 def get_welcome():
88    global ftpcache_key
89    _welcome = urllib._urlopener.ftpcache[ftpcache_key].ftp.welcome
90    ftpcache_key = None # I am assuming there are no duplicate ftp URLs in db.
91                        # If there are - ftpcache_key in prev line is invalid.
92    return _welcome
93
94
95 icons = {} # Icon cache; maps URL to a tuple (content type, data)
96            # or None if there is no icon.
97
98 class robot_simple(Robot):
99    def check_url(self, bookmark):
100       if not self.tempfname:
101          self.tempfname = bookmark.tempfname
102
103       try:
104          try:
105             self.start = int(time.time())
106             bookmark.icon = None
107
108             url_type, url_rest = urllib.splittype(bookmark.href)
109             url_host, url_path = urllib.splithost(url_rest)
110             url_path, url_tag  = urllib.splittag(url_path)
111
112             # Set fake referer to the root of the site
113             urllib._urlopener.addheaders[2] = ('Referer', "%s://%s%s" % (url_type, url_host, url_path))
114
115             if bookmark.charset: urllib._urlopener.addheader('Accept-Charset', bookmark.charset)
116             fname, headers = urllib.urlretrieve("%s://%s%s" % (url_type, url_host, url_path), self.tempfname)
117             if bookmark.charset: del urllib._urlopener.addheaders[-1]
118
119             size = 0
120             last_modified = None
121
122             if headers:
123                try:
124                   size = headers["Content-Length"]
125                except KeyError:
126                   pass
127
128                try:
129                   last_modified = headers["Last-Modified"]
130                except KeyError:
131                   pass
132
133                if last_modified:
134                   last_modified = parse_time(last_modified)
135
136             if last_modified:
137                last_modified = str(int(last_modified))
138             else:
139                last_modified = bookmark.last_visit
140
141             bookmark.size = size
142             bookmark.last_modified = last_modified
143
144             md5 = md5wrapper()
145             if urllib._urlopener.type == "ftp": # Pass welcome message through MD5
146                md5.update(get_welcome())
147
148             md5.md5file(self.tempfname)
149             bookmark.md5 = str(md5)
150
151             if headers:
152                try:
153                   content_type = headers["Content-Type"]
154                   try:
155                      content_type, charset = content_type.split(';')
156                      content_type = content_type.strip()
157                      charset = charset.split('=')[1].strip()
158                      self.log("   HTTP charset   : %s" % charset)
159                   except (ValueError, IndexError):
160                      charset = None
161                      self.log("   no charset in Content-Type header")
162                   if content_type == "text/html":
163                      parser = parse_html(fname, charset, self.log)
164                      bookmark.real_title = parser.title
165                      if parser.refresh:
166                         refresh = parser.refresh
167                         try:
168                            url = refresh.split('=', 1)[1]
169                         except IndexError:
170                            url = "self"
171                         try:
172                            timeout = float(refresh.split(';')[0])
173                         except (IndexError, ValueError):
174                            raise RedirectException("html", "Bad redirect to %s (%s)" % (url, refresh))
175                         else:
176                            try:
177                               timeout = int(refresh.split(';')[0])
178                            except ValueError:
179                               pass # float timeout
180                            raise RedirectException("html", "%s (%s sec)" % (url, timeout))
181
182                      # Get favicon.ico
183                      icon = parser.icon
184                      if not icon:
185                         icon = "/favicon.ico"
186                      icon = urljoin("%s://%s%s" % (url_type, url_host, url_path), icon)
187                      self.log("   looking for icon at: %s" % icon)
188                      if icon in icons:
189                         if icons[icon]:
190                            content_type, bookmark.icon = icons[icon]
191                            self.log("       cached icon: %s" % content_type)
192                         else:
193                            self.log("       cached icon: no icon")
194                      else:
195                         try:
196                            _icon = icon
197                            for i in range(8):
198                               try:
199                                  fname, headers = urllib.urlretrieve(_icon)
200                               except RedirectException, e:
201                                  _icon = e.url
202                                  self.log("       redirect to : %s" % _icon)
203                               else:
204                                  break
205                            else:
206                               raise IOError("Too many redirects")
207                         except:
208                            etype, emsg, tb = sys.exc_info()
209                            self.log("   no icon        : %s %s" % (etype, emsg))
210                            etype = None
211                            emsg = None
212                            tb = None
213                            icons[icon] = None
214                         else:
215                            content_type = headers["Content-Type"]
216                            if content_type.startswith("image/"):
217                               icon_file = open(fname, "rb")
218                               icon = icon_file.read()
219                               icon_file.close()
220                               bookmark.icon = "data:%s;base64,%s" % (content_type, b64encode(icon))
221                               self.log("   got icon       : %s" % content_type)
222                               icons[icon] = (content_type, bookmark.icon)
223                            else:
224                               self.log("   no icon        : bad content type '%s'" % content_type)
225                               icons[icon] = None
226                            os.remove(fname)
227
228                except KeyError:
229                   pass
230
231          except IOError, msg:
232             if (msg[0] == "http error") and (msg[1] == -1):
233                bookmark.no_error = "The server did not return any header - it is not an error, actually"
234             else:
235                bookmark.error = get_error(msg)
236
237          except EOFError:
238             bookmark.error = "Unexpected EOF (FTP server closed connection)"
239
240          except RedirectException, msg:
241             bookmark.moved = str(msg)
242
243          except KeyboardInterrupt:
244             return 0
245
246       finally:
247          self.finish_check_url(bookmark)
248
249       # Tested
250       return 1
251
252
253    def finish_check_url(self, bookmark):
254       # Calculate these attributes even in case of an error
255       if os.path.exists(self.tempfname):
256          size = str(os.path.getsize(self.tempfname))
257          if size[-1] == 'L':
258             size = size[:-1]
259          bookmark.size = size
260
261       start = self.start
262       bookmark.last_tested = str(start)
263
264       now = int(time.time())
265       bookmark.test_time = str(now - start)