]> git.phdru.name Git - bookmarks_db.git/blob - Robots/bkmk_rsimple.py
No need to split bookmark.href - a robot will split it itself.
[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
25
26 class MyURLopener(urllib.URLopener):
27    # Error 302 -- relocated (temporarily)
28    def http_error_302(self, url, fp, errcode, errmsg, headers, data=None): 
29       if headers.has_key('location'):
30          newurl = headers['location']
31       elif headers.has_key('uri'):
32          newurl = headers['uri']
33       else:
34          newurl = "Nowhere"
35       raise RedirectException(errcode, newurl)
36
37    # Error 301 -- also relocated (permanently)
38    http_error_301 = http_error_302
39
40    # Error 401 -- authentication required
41    def http_error_401(self, url, fp, errcode, errmsg, headers, data=None): 
42       raise IOError, ('http error', errcode, "Authentication required ", headers)
43
44
45 urllib._urlopener = MyURLopener()
46
47 # Some sites allow only Mozilla-compatible browsers; way to stop robots?
48 server_version = "Mozilla/3.0 (compatible; Python-urllib/%s)" % urllib.__version__
49 urllib._urlopener.addheaders[0] = ('User-agent', server_version)
50
51
52 def get_error(msg):
53    if type(msg) == type(""):
54       return msg
55
56    else:
57       s = []
58       for i in msg:
59          s.append("'%s'" % string.join(string.split(str(i), "\n"), "\\n"))
60       return "(%s)" % string.join(s)
61
62
63 urllib_ftpwrapper = urllib.ftpwrapper
64 ftpcache_key = None
65
66 class myftpwrapper(urllib_ftpwrapper):
67    def __init__(self, user, passwd, host, port, dirs):
68       urllib_ftpwrapper.__init__(self, user, passwd, host, port, dirs)
69       global ftpcache_key
70       ftpcache_key = (user, host, port, string.join(dirs, '/'))
71
72 urllib.ftpwrapper = myftpwrapper
73
74 def get_welcome():
75    global ftpcache_key
76    _welcome = urllib._urlopener.ftpcache[ftpcache_key].ftp.welcome
77    ftpcache_key = None # I am assuming there are no duplicate ftp URLs in db.
78                        # If there are - ftpcache_key in prev line is invalid.
79    return _welcome
80
81
82 from bkmk_objects import Robot
83 from parse_html import parse_html
84
85 class robot_simple(Robot):
86    def check_url(self, bookmark):
87       if not self.tempfname:
88          self.tempfname = bookmark.tempfname
89
90       try:
91          try:
92             self.start = int(time.time())
93             url_type, url_rest = urllib.splittype(bookmark.href)
94             url_host, url_path = urllib.splithost(url_rest)
95             url_path, url_tag  = urllib.splittag(url_path)
96
97             if bookmark.charset: urllib._urlopener.addheader('Accept-Charset', bookmark.charset)
98             fname, headers = urllib.urlretrieve("%s://%s%s" % (url_type, url_host, url_path), self.tempfname)
99             if bookmark.charset: del urllib._urlopener.addheaders[-1]
100
101             size = 0
102             last_modified = None
103
104             if headers:
105                try:
106                   size = headers["Content-Length"]
107                except KeyError:
108                   pass
109
110                try:
111                   last_modified = headers["Last-Modified"]
112                except KeyError:
113                   pass
114
115                if last_modified:
116                   last_modified = parse_time(last_modified)
117
118             if last_modified:
119                last_modified = str(int(last_modified))
120             else:
121                last_modified = bookmark.last_visit
122
123             bookmark.size = size
124             bookmark.last_modified = last_modified
125
126             md5 = md5wrapper()
127             if urllib._urlopener.type == "ftp": # Pass welcome message through MD5
128                md5.update(get_welcome())
129
130             md5.md5file(self.tempfname)
131             bookmark.md5 = str(md5)
132
133             if headers:
134                try:
135                   content_type = headers["Content-Type"]
136                   try:
137                      content_type, charset = content_type.split(';')
138                      content_type = content_type.strip()
139                      charset = charset.split('=')[1].strip()
140                      if self.log: self.log("   HTTP charset   : %s" % charset)
141                   except (ValueError, IndexError):
142                      charset = None
143                      if self.log: self.log("   no charset in Content-Type header")
144                   if content_type == "text/html":
145                      parser = parse_html(fname, charset, self.log)
146                      title = parser.title.replace('\r', '').replace('\n', ' ').strip()
147                      bookmark.real_title = parser.unescape(title)
148                      if self.log: self.log("   final title    : %s" % bookmark.real_title)
149                      if parser.refresh:
150                         refresh = parser.refresh
151                         try:
152                            url = refresh.split('=', 1)[1]
153                         except IndexError:
154                            url = "self"
155                         try:
156                            timeout = int(refresh.split(';')[0])
157                         except (IndexError, ValueError):
158                            timeout = None
159                         if timeout is None:
160                            raise RedirectException("html", "Bad redirect to %s (%s)" % (url, refresh))
161                         else:
162                            raise RedirectException("html", "%s (%d sec)" % (url, timeout))
163
164                      # Get favicon.ico
165                      icon = parser.icon
166                      if not icon:
167                         icon = "/favicon.ico"
168                      icon = urljoin("%s://%s%s" % (url_type, url_host, url_path), icon)
169                      if self.log: self.log("   icon           : %s" % icon)
170                      try:
171                         fname, headers = urllib.urlretrieve(icon)
172                      except:
173                         etype, emsg, tb = sys.exc_info()
174                         if self.log: self.log("   no icon        : %s %s" % (etype, emsg))
175                         etype = None
176                         emsg = None
177                         tb = None
178                      else:
179                         icon_file = open(fname, "rb")
180                         icon = icon_file.read()
181                         icon_file.close()
182                         os.remove(fname)
183                         content_type = headers["Content-Type"]
184                         bookmark.icon = "data:%s;base64,%s" % (content_type, b64encode(icon))
185
186                except KeyError:
187                   pass
188
189          except IOError, msg:
190             if (msg[0] == "http error") and (msg[1] == -1):
191                bookmark.no_error = "The server did not return any header - it is not an error, actually"
192             else:
193                bookmark.error = get_error(msg)
194
195          except EOFError:
196             bookmark.error = "Unexpected EOF (FTP server closed connection)"
197
198          except RedirectException, msg:
199             bookmark.moved = str(msg)
200
201          except KeyboardInterrupt:
202             return 0
203
204       finally:
205          self.finish_check_url(bookmark)
206
207       # Tested
208       return 1
209
210
211    def finish_check_url(self, bookmark):
212       # Calculate these attributes even in case of an error
213       if os.path.exists(self.tempfname):
214          size = str(os.path.getsize(self.tempfname))
215          if size[-1] == 'L':
216             size = size[:-1]
217          bookmark.size = size
218
219       start = self.start
220       bookmark.last_tested = str(start)
221
222       now = int(time.time())
223       bookmark.test_time = str(now - start)