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