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