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