]> git.phdru.name Git - bookmarks_db.git/blob - bkmk_parser.py
Encode entities.
[bookmarks_db.git] / bkmk_parser.py
1 """
2    Parser for Netscape Navigator's and Mozilla's bookmarks.html
3
4    Written by BroytMann. Copyright (C) 1997-2007 PhiloSoft Design
5 """
6
7
8 import sys, os
9 from m_lib.net.www.html import HTMLParser
10 from bkmk_objects import Folder, Bookmark, Ruler
11
12
13 DEBUG = os.environ.has_key("BKMK_DEBUG")
14
15 if DEBUG:
16    def debug(note):
17       print note
18
19    def dump_names(folder_stack):
20       l = []
21       for object in folder_stack:
22          if object.isFolder:
23             l.append(object.name)
24       return "'%s'" % "' '".join(l)
25
26 else:
27    def debug(note):
28       pass
29    dump_names = debug
30
31
32 DEFAULT_CHARSET = None
33
34 class BkmkParser(HTMLParser):
35    def __init__(self):
36       HTMLParser.__init__(self)
37
38       self.urls = 0
39       self.objects = 0
40
41       self.charset = ""
42       self.recode = None
43
44
45    def handle_data(self, data):
46       if data:
47          if DEFAULT_CHARSET:
48             data = unicode(data, self.charset, "replace").encode(DEFAULT_CHARSET, "xmlcharrefreplace")
49          self.accumulator += data
50
51
52    # Mozilla - get charset
53    def do_meta(self, attrs):
54       http_equiv = ""
55       content = ""
56
57       for attrname, value in attrs:
58          value = value.strip()
59          if attrname == 'http-equiv':
60             http_equiv = value.lower()
61          elif attrname == 'content':
62             content = value
63
64       if http_equiv == "content-type":
65          try:
66             # extract charset from "text/html; charset=UTF-8"
67             self.charset = content.split('=')[1]
68          except IndexError:
69             pass
70          else:
71             global DEFAULT_CHARSET
72             DEFAULT_CHARSET = sys.getdefaultencoding()
73             if DEFAULT_CHARSET == "ascii":
74                try:
75                   import locale
76                except ImportError:
77                   pass
78                else:
79                   DEFAULT_CHARSET = locale.getpreferredencoding()
80
81
82    def start_title(self, attrs):
83       if DEFAULT_CHARSET:
84          self.accumulator += '<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=%s">\n' % DEFAULT_CHARSET
85       self.accumulator += "<TITLE>"
86
87    def end_title(self):
88       self.accumulator += "</TITLE>"
89
90
91    # Start root folder
92    def start_h1(self, attrs):
93       root_folder = Folder()
94       self.current_object = root_folder
95       self.root_folder = root_folder
96       self.current_folder = root_folder
97       self.folder_stack = [root_folder]
98
99       self.root_folder.header = self.accumulator.strip()
100       self.accumulator = ''
101
102    def end_h1(self):
103       accumulator = self.accumulator
104       self.accumulator = ''
105
106       debug("Root folder name: `%s'" % accumulator)
107       self.root_folder.name = accumulator
108
109
110    # Start a folder
111    def start_h3(self, attrs):
112       last_modified = None
113       for attrname, value in attrs:
114          value = value.strip()
115          if attrname == 'add_date':
116             add_date = value
117          elif attrname == 'last_modified':
118             last_modified = value
119
120       debug("New folder...")
121       folder = Folder(add_date, last_modified=last_modified)
122       self.current_object = folder
123       self.current_folder.append(folder)
124       self.folder_stack.append(folder) # push new folder
125       self.current_folder = folder
126       self.objects += 1
127
128    def end_h3(self):
129       accumulator = self.accumulator
130       self.accumulator = ''
131
132       debug("Folder name: `%s'" % accumulator)
133       self.current_folder.name = accumulator
134
135
136    # Start a bookmark
137    def start_a(self, attrs):
138       last_visit = None
139       last_modified = None
140       keyword = None
141       icon = None
142       charset = None
143
144       for attrname, value in attrs:
145          value = value.strip()
146          if attrname == "href":
147             href = value
148          elif attrname == "add_date":
149             add_date = value
150          elif attrname == "last_visit":
151             last_visit = value
152          elif attrname == "last_modified":
153             last_modified = value
154          elif attrname == "shortcuturl":
155             keyword = value
156          elif attrname == "icon":
157             icon = value
158          elif attrname == "last_charset":
159             charset = value
160
161       debug("Bookmark points to: `%s'" % href)
162       bookmark = Bookmark(href, add_date, last_visit, last_modified,
163          keyword or '', '', icon, charset)
164       self.current_object = bookmark
165       self.current_folder.append(bookmark)
166       self.urls += 1
167       self.objects += 1
168
169    def end_a(self):
170       accumulator = self.accumulator
171       self.accumulator = ''
172
173       debug("Bookmark name: `%s'" % accumulator)
174       bookmark = self.current_folder[-1]
175       bookmark.name = accumulator
176
177
178    def flush(self):
179       accumulator = self.accumulator
180
181       if accumulator:
182          self.accumulator = ''
183
184          current_object = self.current_object
185          if current_object:
186             current_object.comment += accumulator.strip()
187             debug("Comment: `%s'" % current_object.comment)
188
189
190    def start_dl(self, attrs):
191       self.flush()
192
193    do_dt = start_dl
194
195
196    # End of folder
197    def end_dl(self):
198       self.flush()
199       debug("End folder")
200       debug("Folder stack: %s" % dump_names(self.folder_stack))
201       if self.folder_stack:
202          del self.folder_stack[-1] # pop last folder
203          if self.folder_stack:
204             self.current_folder = self.folder_stack[-1]
205          else:
206             debug("FOLDER STACK is EMPTY!!! (1)")
207       else:
208          debug("FOLDER STACK is EMPTY!!! (2)")
209       self.current_object = None
210
211
212    def close(self):
213       HTMLParser.close(self)
214       if self.folder_stack:
215          raise ValueError, "wrong folder stack: %s" % self.folder_stack
216
217
218    def do_dd(self, attrs):
219       pass
220
221    do_p = do_dd
222
223
224    # Start ruler
225    def do_hr(self, attrs):
226       self.flush()
227       debug("Ruler")
228       self.current_folder.append(Ruler())
229       self.current_object = None
230       self.objects += 1
231
232
233    # BR in comment
234    def do_br(self, attrs):
235       self.accumulator += "<BR>"
236
237
238    # Allow < in the text
239    def unknown_starttag(self, tag, attrs):
240       self.accumulator += "<%s>" % tag
241
242
243    # Do not allow unknow end tags
244    def unknown_endtag(self, tag):
245       raise NotImplementedError("Unknow end tag `%s'" % tag)