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