]> git.phdru.name Git - bookmarks_db.git/blob - Robots/bkmk_robot_base.py
Feat(Python3): `except Error, value` -> `except Error as value`
[bookmarks_db.git] / Robots / bkmk_robot_base.py
1 """Base class for robots
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-2017 PhiloSoft Design"
9 __license__ = "GNU GPL"
10
11 __all__ = ['robot_base', 'get_error']
12
13
14 from base64 import b64encode
15 import sys
16 import socket
17 import time
18 import urllib
19 from urlparse import urljoin
20
21 from m_lib.md5wrapper import md5wrapper
22 from m_lib.net.www.util import parse_time
23
24 from bkmk_objects import Robot
25 from parse_html import parse_html
26
27
28 reloc_dict = {
29   301: "perm.",
30   302: "temp2.",
31   303: "temp3.",
32   307: "temp7.",
33   "html": "html"
34 }
35
36
37 def get_error(e):
38    if isinstance(e, str):
39       return e
40
41    else:
42       s = []
43       for i in e:
44          s.append("'%s'" % str(i).replace('\n', "\\n"))
45       return "(%s)" % ' '.join(s)
46
47
48 icons = {} # Icon cache; maps URL to a tuple (content type, data)
49            # or None if there is no icon.
50
51 class robot_base(Robot):
52    timeout = 60
53
54    def __init__(self, *args, **kw):
55         Robot.__init__(self, *args, **kw)
56         socket.setdefaulttimeout(int(self.timeout))
57
58    def check_url(self, bookmark):
59       try:
60          self.start = int(time.time())
61          bookmark.icon = None
62
63          url_type, url_rest = urllib.splittype(bookmark.href)
64          url_host, url_path = urllib.splithost(url_rest)
65          url_path, url_tag  = urllib.splittag(url_path)
66
67          url = "%s://%s%s" % (url_type, url_host, url_path)
68          error, redirect_code, redirect_to, headers, content = self.get(bookmark, url, True)
69
70          if error:
71              bookmark.error = error
72              return 1
73
74          if redirect_code:
75              self.set_redirect(bookmark, redirect_code, redirect_to)
76              return 1
77
78          size = 0
79          last_modified = None
80
81          if headers:
82             try:
83                size = headers["Content-Length"]
84             except KeyError:
85                size = len(content)
86
87             try:
88                last_modified = headers["Last-Modified"]
89             except KeyError:
90                pass
91
92             if last_modified:
93                last_modified = parse_time(last_modified)
94          else:
95             size = len(content)
96
97          if last_modified:
98             last_modified = str(int(last_modified))
99          else:
100             last_modified = bookmark.last_visit
101
102          bookmark.size = size
103          bookmark.last_modified = last_modified
104
105          md5 = md5wrapper()
106          if url_type == "ftp": # Pass welcome message through MD5
107             md5.update(self.get_ftp_welcome())
108
109          md5.update(content)
110          bookmark.md5 = str(md5)
111
112          if headers:
113             try:
114                content_type = headers["Content-Type"]
115                self.log("   Content-Type: %s" % content_type)
116                try:
117                   # extract charset from "text/html; foo; charset=UTF-8, bar; baz;"
118                   content_type, charset = content_type.split(';', 1)
119                   content_type = content_type.strip()
120                   charset = charset.split('=')[1].strip().split(',')[0]
121                   self.log("   HTTP charset   : %s" % charset)
122                except (ValueError, IndexError):
123                   charset = None
124                   self.log("   no charset in Content-Type header")
125                for ctype in ("text/html", "application/xhtml+xml"):
126                   if content_type.startswith(ctype):
127                       html = True
128                       break
129                else:
130                   html = False
131                if html:
132                   parser = parse_html(content, charset, self.log)
133                   if parser:
134                       bookmark.real_title = parser.title
135                       icon = parser.icon
136                   else:
137                      icon = None
138                   if not icon:
139                      icon = "/favicon.ico"
140                   icon_url = urljoin("%s://%s%s" % (url_type, url_host, url_path), icon)
141                   self.log("   looking for icon at: %s" % icon_url)
142                   if icon_url in icons:
143                      if icons[icon_url]:
144                         bookmark.icon_href = icon_url
145                         content_type, bookmark.icon = icons[icon_url]
146                         self.log("   cached icon: %s" % content_type)
147                      else:
148                         self.log("   cached icon: no icon")
149                   else:
150                      try:
151                         _icon_url = icon_url
152                         for i in range(8):
153                            error, icon_redirect_code, icon_redirect_to, \
154                               icon_headers, icon_data = \
155                                  self.get(bookmark, _icon_url)
156                            if icon_redirect_code:
157                               _icon_url = icon_redirect_to
158                               self.log("   redirect to : %s" % _icon_url)
159                            else:
160                               if icon_data is None:
161                                    raise IOError("No icon")
162                               break
163                         else:
164                            raise IOError("Too many redirects")
165                      except:
166                         etype, emsg, tb = sys.exc_info()
167                         self.log("   no icon        : %s %s" % (etype, emsg))
168                         etype = emsg = tb = None
169                         icons[icon_url] = None
170                      else:
171                         content_type = icon_headers["Content-Type"]
172                         if content_type.startswith("application/") \
173                               or content_type.startswith("image/") \
174                               or content_type.startswith("text/plain"):
175                            bookmark.icon_href = icon_url
176                            self.log("   got icon       : %s" % content_type)
177                            if content_type.startswith("application/") \
178                                  or content_type.startswith("text/plain"):
179                               self.log("   non-image content type, assume x-icon")
180                               content_type = 'image/x-icon'
181                            bookmark.icon = "data:%s;base64,%s" % (content_type, b64encode(icon_data))
182                            icons[icon_url] = (content_type, bookmark.icon)
183                         else:
184                            self.log("   no icon        : bad content type '%s'" % content_type)
185                            icons[icon_url] = None
186                   if parser and parser.refresh:
187                      refresh = parser.refresh
188                      try:
189                         url = refresh.split('=', 1)[1]
190                      except IndexError:
191                         url = "self"
192                      try:
193                         timeout = float(refresh.split(';')[0])
194                      except (IndexError, ValueError):
195                         self.set_redirect(bookmark, "html", "Bad redirect to %s (%s)" % (url, refresh))
196                      else:
197                         try:
198                            timeout = int(refresh.split(';')[0])
199                         except ValueError:
200                            pass # float timeout
201                         self.set_redirect(bookmark, "html", "%s (%s sec)" % (url, timeout))
202
203             except KeyError as key:
204                self.log("   no header: %s" % key)
205
206       except EOFError:
207          bookmark.error = "Unexpected EOF (FTP server closed connection)"
208          self.log('   EOF: %s' % bookmark.error)
209
210       except KeyboardInterrupt:
211          self.log("Keyboard interrupt (^C)")
212          return 0
213
214       except socket.error as e:
215          bookmark.error = get_error(e)
216          self.log(bookmark.error)
217
218       except:
219          import traceback
220          traceback.print_exc()
221          bookmark.error = "Exception!"
222          self.log('   Exception: %s' % bookmark.error)
223
224       finally:
225          self.finish_check_url(bookmark)
226
227       # Tested
228       return 1
229
230    def set_redirect(self, bookmark, errcode, newurl):
231         bookmark.moved = "(%s) to %s" % (reloc_dict[errcode], newurl)
232         self.log('   Moved: %s' % bookmark.moved)
233
234    def finish_check_url(self, bookmark):
235       start = self.start
236       bookmark.last_tested = str(start)
237       now = int(time.time())
238       bookmark.test_time = str(now - start)