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