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