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